// Code generated by Stan version 2.21.0

#include <stan/model/model_header.hpp>

namespace model8d0c1a161196_stan_8d0c707b268e_namespace {

using std::istream;
using std::string;
using std::stringstream;
using std::vector;
using stan::io::dump;
using stan::math::lgamma;
using stan::model::prob_grad;
using namespace stan::math;

static int current_statement_begin__;

stan::io::program_reader prog_reader__() {
    stan::io::program_reader reader;
    reader.add_event(0, 0, "start", "model8d0c1a161196_stan_8d0c707b268e");
    reader.add_event(27, 25, "end", "model8d0c1a161196_stan_8d0c707b268e");
    return reader;
}

class model8d0c1a161196_stan_8d0c707b268e
  : public stan::model::model_base_crtp<model8d0c1a161196_stan_8d0c707b268e> {
private:
        int N;
        int D;
        int K;
        int M;
        std::vector<int> X;
public:
    model8d0c1a161196_stan_8d0c707b268e(rstan::io::rlist_ref_var_context& context__,
        std::ostream* pstream__ = 0)
        : model_base_crtp(0) {
        ctor_body(context__, 0, pstream__);
    }

    model8d0c1a161196_stan_8d0c707b268e(stan::io::var_context& context__,
        unsigned int random_seed__,
        std::ostream* pstream__ = 0)
        : model_base_crtp(0) {
        ctor_body(context__, random_seed__, pstream__);
    }

    void ctor_body(stan::io::var_context& context__,
                   unsigned int random_seed__,
                   std::ostream* pstream__) {
        typedef double local_scalar_t__;

        boost::ecuyer1988 base_rng__ =
          stan::services::util::create_rng(random_seed__, 0);
        (void) base_rng__;  // suppress unused var warning

        current_statement_begin__ = -1;

        static const char* function__ = "model8d0c1a161196_stan_8d0c707b268e_namespace::model8d0c1a161196_stan_8d0c707b268e";
        (void) function__;  // dummy to suppress unused var warning
        size_t pos__;
        (void) pos__;  // dummy to suppress unused var warning
        std::vector<int> vals_i__;
        std::vector<double> vals_r__;
        local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
        (void) DUMMY_VAR__;  // suppress unused var warning

        try {
            // initialize data block variables from context__
            current_statement_begin__ = 3;
            context__.validate_dims("data initialization", "N", "int", context__.to_vec());
            N = int(0);
            vals_i__ = context__.vals_i("N");
            pos__ = 0;
            N = vals_i__[pos__++];
            check_greater_or_equal(function__, "N", N, 0);

            current_statement_begin__ = 4;
            context__.validate_dims("data initialization", "D", "int", context__.to_vec());
            D = int(0);
            vals_i__ = context__.vals_i("D");
            pos__ = 0;
            D = vals_i__[pos__++];
            check_greater_or_equal(function__, "D", D, 0);

            current_statement_begin__ = 5;
            context__.validate_dims("data initialization", "K", "int", context__.to_vec());
            K = int(0);
            vals_i__ = context__.vals_i("K");
            pos__ = 0;
            K = vals_i__[pos__++];
            check_greater_or_equal(function__, "K", K, 0);

            current_statement_begin__ = 6;
            context__.validate_dims("data initialization", "M", "int", context__.to_vec());
            M = int(0);
            vals_i__ = context__.vals_i("M");
            pos__ = 0;
            M = vals_i__[pos__++];
            check_greater_or_equal(function__, "M", M, 0);

            current_statement_begin__ = 7;
            validate_non_negative_index("X", "(N * D)", (N * D));
            context__.validate_dims("data initialization", "X", "int", context__.to_vec((N * D)));
            X = std::vector<int>((N * D), int(0));
            vals_i__ = context__.vals_i("X");
            pos__ = 0;
            size_t X_k_0_max__ = (N * D);
            for (size_t k_0__ = 0; k_0__ < X_k_0_max__; ++k_0__) {
                X[k_0__] = vals_i__[pos__++];
            }
            size_t X_i_0_max__ = (N * D);
            for (size_t i_0__ = 0; i_0__ < X_i_0_max__; ++i_0__) {
                check_greater_or_equal(function__, "X[i_0__]", X[i_0__], 0);
                check_less_or_equal(function__, "X[i_0__]", X[i_0__], M);
            }


            // initialize transformed data variables
            // execute transformed data statements

            // validate transformed data

            // validate, set parameter ranges
            num_params_r__ = 0U;
            param_ranges_i__.clear();
            current_statement_begin__ = 11;
            validate_non_negative_index("Z", "N", N);
            validate_non_negative_index("Z", "K", K);
            num_params_r__ += (N * K);
            current_statement_begin__ = 12;
            validate_non_negative_index("W", "D", D);
            validate_non_negative_index("W", "K", K);
            num_params_r__ += (D * K);
            current_statement_begin__ = 13;
            validate_non_negative_index("alpha", "K", K);
            num_params_r__ += K;
        } catch (const std::exception& e) {
            stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__());
            // Next line prevents compiler griping about no return
            throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***");
        }
    }

    ~model8d0c1a161196_stan_8d0c707b268e() { }


    void transform_inits(const stan::io::var_context& context__,
                         std::vector<int>& params_i__,
                         std::vector<double>& params_r__,
                         std::ostream* pstream__) const {
        typedef double local_scalar_t__;
        stan::io::writer<double> writer__(params_r__, params_i__);
        size_t pos__;
        (void) pos__; // dummy call to supress warning
        std::vector<double> vals_r__;
        std::vector<int> vals_i__;

        current_statement_begin__ = 11;
        if (!(context__.contains_r("Z")))
            stan::lang::rethrow_located(std::runtime_error(std::string("Variable Z missing")), current_statement_begin__, prog_reader__());
        vals_r__ = context__.vals_r("Z");
        pos__ = 0U;
        validate_non_negative_index("Z", "N", N);
        validate_non_negative_index("Z", "K", K);
        context__.validate_dims("parameter initialization", "Z", "matrix_d", context__.to_vec(N,K));
        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Z(N, K);
        size_t Z_j_2_max__ = K;
        size_t Z_j_1_max__ = N;
        for (size_t j_2__ = 0; j_2__ < Z_j_2_max__; ++j_2__) {
            for (size_t j_1__ = 0; j_1__ < Z_j_1_max__; ++j_1__) {
                Z(j_1__, j_2__) = vals_r__[pos__++];
            }
        }
        try {
            writer__.matrix_unconstrain(Z);
        } catch (const std::exception& e) {
            stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable Z: ") + e.what()), current_statement_begin__, prog_reader__());
        }

        current_statement_begin__ = 12;
        if (!(context__.contains_r("W")))
            stan::lang::rethrow_located(std::runtime_error(std::string("Variable W missing")), current_statement_begin__, prog_reader__());
        vals_r__ = context__.vals_r("W");
        pos__ = 0U;
        validate_non_negative_index("W", "D", D);
        validate_non_negative_index("W", "K", K);
        context__.validate_dims("parameter initialization", "W", "matrix_d", context__.to_vec(D,K));
        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W(D, K);
        size_t W_j_2_max__ = K;
        size_t W_j_1_max__ = D;
        for (size_t j_2__ = 0; j_2__ < W_j_2_max__; ++j_2__) {
            for (size_t j_1__ = 0; j_1__ < W_j_1_max__; ++j_1__) {
                W(j_1__, j_2__) = vals_r__[pos__++];
            }
        }
        try {
            writer__.matrix_unconstrain(W);
        } catch (const std::exception& e) {
            stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable W: ") + e.what()), current_statement_begin__, prog_reader__());
        }

        current_statement_begin__ = 13;
        if (!(context__.contains_r("alpha")))
            stan::lang::rethrow_located(std::runtime_error(std::string("Variable alpha missing")), current_statement_begin__, prog_reader__());
        vals_r__ = context__.vals_r("alpha");
        pos__ = 0U;
        validate_non_negative_index("alpha", "K", K);
        context__.validate_dims("parameter initialization", "alpha", "vector_d", context__.to_vec(K));
        Eigen::Matrix<double, Eigen::Dynamic, 1> alpha(K);
        size_t alpha_j_1_max__ = K;
        for (size_t j_1__ = 0; j_1__ < alpha_j_1_max__; ++j_1__) {
            alpha(j_1__) = vals_r__[pos__++];
        }
        try {
            writer__.vector_lb_unconstrain(0, alpha);
        } catch (const std::exception& e) {
            stan::lang::rethrow_located(std::runtime_error(std::string("Error transforming variable alpha: ") + e.what()), current_statement_begin__, prog_reader__());
        }

        params_r__ = writer__.data_r();
        params_i__ = writer__.data_i();
    }

    void transform_inits(const stan::io::var_context& context,
                         Eigen::Matrix<double, Eigen::Dynamic, 1>& params_r,
                         std::ostream* pstream__) const {
      std::vector<double> params_r_vec;
      std::vector<int> params_i_vec;
      transform_inits(context, params_i_vec, params_r_vec, pstream__);
      params_r.resize(params_r_vec.size());
      for (int i = 0; i < params_r.size(); ++i)
        params_r(i) = params_r_vec[i];
    }


    template <bool propto__, bool jacobian__, typename T__>
    T__ log_prob(std::vector<T__>& params_r__,
                 std::vector<int>& params_i__,
                 std::ostream* pstream__ = 0) const {

        typedef T__ local_scalar_t__;

        local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
        (void) DUMMY_VAR__;  // dummy to suppress unused var warning

        T__ lp__(0.0);
        stan::math::accumulator<T__> lp_accum__;
        try {
            stan::io::reader<local_scalar_t__> in__(params_r__, params_i__);

            // model parameters
            current_statement_begin__ = 11;
            Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> Z;
            (void) Z;  // dummy to suppress unused var warning
            if (jacobian__)
                Z = in__.matrix_constrain(N, K, lp__);
            else
                Z = in__.matrix_constrain(N, K);

            current_statement_begin__ = 12;
            Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic> W;
            (void) W;  // dummy to suppress unused var warning
            if (jacobian__)
                W = in__.matrix_constrain(D, K, lp__);
            else
                W = in__.matrix_constrain(D, K);

            current_statement_begin__ = 13;
            Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> alpha;
            (void) alpha;  // dummy to suppress unused var warning
            if (jacobian__)
                alpha = in__.vector_lb_constrain(0, K, lp__);
            else
                alpha = in__.vector_lb_constrain(0, K);

            // transformed parameters
            current_statement_begin__ = 17;
            validate_non_negative_index("t_alpha", "K", K);
            Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1> t_alpha(K);
            stan::math::initialize(t_alpha, DUMMY_VAR__);
            stan::math::fill(t_alpha, DUMMY_VAR__);

            // transformed parameters block statements
            current_statement_begin__ = 18;
            stan::math::assign(t_alpha, inv(stan::math::sqrt(alpha)));

            // validate transformed parameters
            const char* function__ = "validate transformed params";
            (void) function__;  // dummy to suppress unused var warning

            current_statement_begin__ = 17;
            size_t t_alpha_j_1_max__ = K;
            for (size_t j_1__ = 0; j_1__ < t_alpha_j_1_max__; ++j_1__) {
                if (stan::math::is_uninitialized(t_alpha(j_1__))) {
                    std::stringstream msg__;
                    msg__ << "Undefined transformed parameter: t_alpha" << "(" << j_1__ << ")";
                    stan::lang::rethrow_located(std::runtime_error(std::string("Error initializing variable t_alpha: ") + msg__.str()), current_statement_begin__, prog_reader__());
                }
            }
            check_greater_or_equal(function__, "t_alpha", t_alpha, 0);


            // model body

            current_statement_begin__ = 21;
            lp_accum__.add(normal_log<propto__>(to_vector(Z), 0, 1));
            current_statement_begin__ = 22;
            lp_accum__.add(gamma_log<propto__>(alpha, 1e-3, 1e-3));
            current_statement_begin__ = 23;
            for (int k = 1; k <= K; ++k) {
                current_statement_begin__ = 23;
                lp_accum__.add(normal_log<propto__>(stan::model::rvalue(W, stan::model::cons_list(stan::model::index_omni(), stan::model::cons_list(stan::model::index_uni(k), stan::model::nil_index_list())), "W"), 0, get_base1(t_alpha, k, "t_alpha", 1)));
            }
            current_statement_begin__ = 24;
            lp_accum__.add(binomial_logit_log<propto__>(X, M, to_vector(multiply(Z, transpose(W)))));

        } catch (const std::exception& e) {
            stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__());
            // Next line prevents compiler griping about no return
            throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***");
        }

        lp_accum__.add(lp__);
        return lp_accum__.sum();

    } // log_prob()

    template <bool propto, bool jacobian, typename T_>
    T_ log_prob(Eigen::Matrix<T_,Eigen::Dynamic,1>& params_r,
               std::ostream* pstream = 0) const {
      std::vector<T_> vec_params_r;
      vec_params_r.reserve(params_r.size());
      for (int i = 0; i < params_r.size(); ++i)
        vec_params_r.push_back(params_r(i));
      std::vector<int> vec_params_i;
      return log_prob<propto,jacobian,T_>(vec_params_r, vec_params_i, pstream);
    }


    void get_param_names(std::vector<std::string>& names__) const {
        names__.resize(0);
        names__.push_back("Z");
        names__.push_back("W");
        names__.push_back("alpha");
        names__.push_back("t_alpha");
    }


    void get_dims(std::vector<std::vector<size_t> >& dimss__) const {
        dimss__.resize(0);
        std::vector<size_t> dims__;
        dims__.resize(0);
        dims__.push_back(N);
        dims__.push_back(K);
        dimss__.push_back(dims__);
        dims__.resize(0);
        dims__.push_back(D);
        dims__.push_back(K);
        dimss__.push_back(dims__);
        dims__.resize(0);
        dims__.push_back(K);
        dimss__.push_back(dims__);
        dims__.resize(0);
        dims__.push_back(K);
        dimss__.push_back(dims__);
    }

    template <typename RNG>
    void write_array(RNG& base_rng__,
                     std::vector<double>& params_r__,
                     std::vector<int>& params_i__,
                     std::vector<double>& vars__,
                     bool include_tparams__ = true,
                     bool include_gqs__ = true,
                     std::ostream* pstream__ = 0) const {
        typedef double local_scalar_t__;

        vars__.resize(0);
        stan::io::reader<local_scalar_t__> in__(params_r__, params_i__);
        static const char* function__ = "model8d0c1a161196_stan_8d0c707b268e_namespace::write_array";
        (void) function__;  // dummy to suppress unused var warning

        // read-transform, write parameters
        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Z = in__.matrix_constrain(N, K);
        size_t Z_j_2_max__ = K;
        size_t Z_j_1_max__ = N;
        for (size_t j_2__ = 0; j_2__ < Z_j_2_max__; ++j_2__) {
            for (size_t j_1__ = 0; j_1__ < Z_j_1_max__; ++j_1__) {
                vars__.push_back(Z(j_1__, j_2__));
            }
        }

        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W = in__.matrix_constrain(D, K);
        size_t W_j_2_max__ = K;
        size_t W_j_1_max__ = D;
        for (size_t j_2__ = 0; j_2__ < W_j_2_max__; ++j_2__) {
            for (size_t j_1__ = 0; j_1__ < W_j_1_max__; ++j_1__) {
                vars__.push_back(W(j_1__, j_2__));
            }
        }

        Eigen::Matrix<double, Eigen::Dynamic, 1> alpha = in__.vector_lb_constrain(0, K);
        size_t alpha_j_1_max__ = K;
        for (size_t j_1__ = 0; j_1__ < alpha_j_1_max__; ++j_1__) {
            vars__.push_back(alpha(j_1__));
        }

        double lp__ = 0.0;
        (void) lp__;  // dummy to suppress unused var warning
        stan::math::accumulator<double> lp_accum__;

        local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN());
        (void) DUMMY_VAR__;  // suppress unused var warning

        if (!include_tparams__ && !include_gqs__) return;

        try {
            // declare and define transformed parameters
            current_statement_begin__ = 17;
            validate_non_negative_index("t_alpha", "K", K);
            Eigen::Matrix<double, Eigen::Dynamic, 1> t_alpha(K);
            stan::math::initialize(t_alpha, DUMMY_VAR__);
            stan::math::fill(t_alpha, DUMMY_VAR__);

            // do transformed parameters statements
            current_statement_begin__ = 18;
            stan::math::assign(t_alpha, inv(stan::math::sqrt(alpha)));

            if (!include_gqs__ && !include_tparams__) return;
            // validate transformed parameters
            const char* function__ = "validate transformed params";
            (void) function__;  // dummy to suppress unused var warning

            current_statement_begin__ = 17;
            check_greater_or_equal(function__, "t_alpha", t_alpha, 0);

            // write transformed parameters
            if (include_tparams__) {
                size_t t_alpha_j_1_max__ = K;
                for (size_t j_1__ = 0; j_1__ < t_alpha_j_1_max__; ++j_1__) {
                    vars__.push_back(t_alpha(j_1__));
                }
            }
            if (!include_gqs__) return;
        } catch (const std::exception& e) {
            stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__());
            // Next line prevents compiler griping about no return
            throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***");
        }
    }

    template <typename RNG>
    void write_array(RNG& base_rng,
                     Eigen::Matrix<double,Eigen::Dynamic,1>& params_r,
                     Eigen::Matrix<double,Eigen::Dynamic,1>& vars,
                     bool include_tparams = true,
                     bool include_gqs = true,
                     std::ostream* pstream = 0) const {
      std::vector<double> params_r_vec(params_r.size());
      for (int i = 0; i < params_r.size(); ++i)
        params_r_vec[i] = params_r(i);
      std::vector<double> vars_vec;
      std::vector<int> params_i_vec;
      write_array(base_rng, params_r_vec, params_i_vec, vars_vec, include_tparams, include_gqs, pstream);
      vars.resize(vars_vec.size());
      for (int i = 0; i < vars.size(); ++i)
        vars(i) = vars_vec[i];
    }

    std::string model_name() const {
        return "model8d0c1a161196_stan_8d0c707b268e";
    }


    void constrained_param_names(std::vector<std::string>& param_names__,
                                 bool include_tparams__ = true,
                                 bool include_gqs__ = true) const {
        std::stringstream param_name_stream__;
        size_t Z_j_2_max__ = K;
        size_t Z_j_1_max__ = N;
        for (size_t j_2__ = 0; j_2__ < Z_j_2_max__; ++j_2__) {
            for (size_t j_1__ = 0; j_1__ < Z_j_1_max__; ++j_1__) {
                param_name_stream__.str(std::string());
                param_name_stream__ << "Z" << '.' << j_1__ + 1 << '.' << j_2__ + 1;
                param_names__.push_back(param_name_stream__.str());
            }
        }
        size_t W_j_2_max__ = K;
        size_t W_j_1_max__ = D;
        for (size_t j_2__ = 0; j_2__ < W_j_2_max__; ++j_2__) {
            for (size_t j_1__ = 0; j_1__ < W_j_1_max__; ++j_1__) {
                param_name_stream__.str(std::string());
                param_name_stream__ << "W" << '.' << j_1__ + 1 << '.' << j_2__ + 1;
                param_names__.push_back(param_name_stream__.str());
            }
        }
        size_t alpha_j_1_max__ = K;
        for (size_t j_1__ = 0; j_1__ < alpha_j_1_max__; ++j_1__) {
            param_name_stream__.str(std::string());
            param_name_stream__ << "alpha" << '.' << j_1__ + 1;
            param_names__.push_back(param_name_stream__.str());
        }

        if (!include_gqs__ && !include_tparams__) return;

        if (include_tparams__) {
            size_t t_alpha_j_1_max__ = K;
            for (size_t j_1__ = 0; j_1__ < t_alpha_j_1_max__; ++j_1__) {
                param_name_stream__.str(std::string());
                param_name_stream__ << "t_alpha" << '.' << j_1__ + 1;
                param_names__.push_back(param_name_stream__.str());
            }
        }

        if (!include_gqs__) return;
    }


    void unconstrained_param_names(std::vector<std::string>& param_names__,
                                   bool include_tparams__ = true,
                                   bool include_gqs__ = true) const {
        std::stringstream param_name_stream__;
        size_t Z_j_2_max__ = K;
        size_t Z_j_1_max__ = N;
        for (size_t j_2__ = 0; j_2__ < Z_j_2_max__; ++j_2__) {
            for (size_t j_1__ = 0; j_1__ < Z_j_1_max__; ++j_1__) {
                param_name_stream__.str(std::string());
                param_name_stream__ << "Z" << '.' << j_1__ + 1 << '.' << j_2__ + 1;
                param_names__.push_back(param_name_stream__.str());
            }
        }
        size_t W_j_2_max__ = K;
        size_t W_j_1_max__ = D;
        for (size_t j_2__ = 0; j_2__ < W_j_2_max__; ++j_2__) {
            for (size_t j_1__ = 0; j_1__ < W_j_1_max__; ++j_1__) {
                param_name_stream__.str(std::string());
                param_name_stream__ << "W" << '.' << j_1__ + 1 << '.' << j_2__ + 1;
                param_names__.push_back(param_name_stream__.str());
            }
        }
        size_t alpha_j_1_max__ = K;
        for (size_t j_1__ = 0; j_1__ < alpha_j_1_max__; ++j_1__) {
            param_name_stream__.str(std::string());
            param_name_stream__ << "alpha" << '.' << j_1__ + 1;
            param_names__.push_back(param_name_stream__.str());
        }

        if (!include_gqs__ && !include_tparams__) return;

        if (include_tparams__) {
            size_t t_alpha_j_1_max__ = K;
            for (size_t j_1__ = 0; j_1__ < t_alpha_j_1_max__; ++j_1__) {
                param_name_stream__.str(std::string());
                param_name_stream__ << "t_alpha" << '.' << j_1__ + 1;
                param_names__.push_back(param_name_stream__.str());
            }
        }

        if (!include_gqs__) return;
    }

}; // model

}  // namespace

typedef model8d0c1a161196_stan_8d0c707b268e_namespace::model8d0c1a161196_stan_8d0c707b268e stan_model;

#ifndef USING_R

stan::model::model_base& new_model(
        stan::io::var_context& data_context,
        unsigned int seed,
        std::ostream* msg_stream) {
  stan_model* m = new stan_model(data_context, seed, msg_stream);
  return *m;
}

#endif