<commit_before>#ifndef DRAKE_OPTIMIZATION_H
#define DRAKE_OPTIMIZATION_H

#include "Core.h"
#include <list>
#include <memory>
#include <initializer_list>

namespace Drake {

  class DecisionVariable {
    enum VarType {
      CONTINUOUS,
      INTEGER,
      BINARY
    };

    /** index()
     * @brief returns the first index of this variable in the entire variable vector for the program
     */
    size_t index() const { return start_index; }
    /** size()
     * @brief returns the number of elements in the decision variable vector
     */
    size_t size() const { return data.size(); }
    /** value()
     * @brief returns the actual stored value; which is only meaningful after calling solve() in the program.
     */
    const Eigen::VectorXd& value() const { return data; }

    VarType type;
    std::string name;     // todo: make this a vector of strings

    friend class OptimizationProblem;
    friend class DecisionVariableView;

  private:
    Eigen::VectorXd data;
    size_t start_index;
  };
  class DecisionVariableView {  // enables users to access pieces of the decision variables like they would any other eigen vector
  public:
    DecisionVariableView(const DecisionVariable& var) : var(var), start_index(0), length(var.data.rows()) {}
    DecisionVariableView(const DecisionVariable& var, size_t start, size_t n) : var(var), start_index(start), length(n) {
      assert(start+n<var.data.rows());
    }

    /** index()
     * @brief returns the first index of this variable in the entire variable vector for the program
     */
    size_t index() const { return var.start_index + start_index; }
    /** size()
     * @brief returns the number of elements in the decision variable vector
     */
    size_t size() const { return length; }
    /** value()
     * @brief returns the actual stored value; which is only meaningful after calling solve() in the program.
     */
    Eigen::VectorBlock<const Eigen::VectorXd,-1> value() const { return var.data.segment(start_index,length); }

    const DecisionVariableView operator()(size_t i) const { assert(i<=length); return DecisionVariableView(var,start_index+i,1);}
    const DecisionVariableView row(size_t i) const { assert(i<=length); return DecisionVariableView(var,start_index+i,1); }
    const DecisionVariableView head(size_t n) const { assert(n<=length); return DecisionVariableView(var,start_index,n); }
    const DecisionVariableView tail(size_t n) const { assert(n<=length); return DecisionVariableView(var,start_index+length-n,n); }
    const DecisionVariableView segment(size_t start, size_t n) const { assert(start+n<=length); return DecisionVariableView(var,start_index+start,n); }

    friend class OptimizationProblem;

  private:
    const DecisionVariable& var;
    size_t start_index, length;
  };

  typedef std::list<DecisionVariableView> VariableList;

  // Quick notes about this design:
  // need to have lists of constraints (if not functions), so I want a (non-templated) base class.
  // would be nice to have templated types for specialized functions.  Not strictly required.
  // approach: let functions be templated, and use lambda closures/std::function to wrap them into the constraint classes.

  /**
   * @defgroup function_concept Function Concept
   * @ingroup concepts
   * @{
   * @brief Describes a mapping from one Vector to another Vector y = f(x)
   *
   * @nbsp
   *
   * | Every model of this concept must implement |  |
   * ---------------------|------------------------------------------------------------|
   * | X::InputVector     | type for the input to the system, which models the Vector<ScalarType> concept |
   * | X::OutputVector    | type for the output from the system, which models the Vector<ScalarType> concept |
   * | template <ScalarType> OutputVector<ScalarType> operator()(const InputVector<ScalarType>& x) | the actual function |
   * | InputOutputRelation getProperties() | |
   * | size_t getNumInputs() | only required if the input vector is dynamically-sized |
   * | size_t getNumOutputs() | only required if the output vector is dynamically-sized |
   *
   * (always try to label your methods with const if possible)
   *
   * @}
   */

  /*
   * some thoughts: a constraint is a function + lower and upper bounds.  it should support evaluating the constraint, adding it to an optimization problem,
   * and have support for constraints that require slack variables (adding additional decision variables to the problem).  There
   * should also be some notion of parameterized constraints:  e.g. the acceleration constraints in the rigid body dynamics are constraints
   * on vdot and f, but are "parameterized" by q and v.
   */
  class Constraint {
  public:
    Constraint(const VariableList& vars) : variable_list(vars) {}
    virtual ~Constraint() {}

    const VariableList& getVariableList() const { return variable_list; }
  protected:
    VariableList variable_list;
  };

  // DifferentiableConstraint, PolynomialConstraint, QuadraticConstraint, ComplementarityConstraint, IntegerConstraint, ...

  /** LinearEqualityConstraint
   * @brief Implements a constraint of the form @f Ax = b @f
   */
  class LinearEqualityConstraint : public Constraint {
  public:
    LinearEqualityConstraint(const VariableList& vars) : Constraint(vars) {}
    virtual ~LinearEqualityConstraint() {}

    virtual const Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> & getMatrix() const = 0;
    virtual const Eigen::Matrix<double,Eigen::Dynamic,1>& getVector() const = 0;
  };

  class LinearEqualityConstraintImpl : public LinearEqualityConstraint {
  public:
    template <typename DerivedA,typename DerivedB>
    LinearEqualityConstraintImpl(const VariableList& vars, const Eigen::MatrixBase<DerivedA>& Aeq, const Eigen::MatrixBase<DerivedB>& beq)
            : A(Aeq), b(beq), LinearEqualityConstraint(vars) {
      assert(A.rows()==b.rows());
      // todo: only do this loop if debug mode (only used for assert)
      int num_referenced_vars = 0;
      for (const DecisionVariableView& v : vars) {
        num_referenced_vars += v.size();
      }
      assert(A.cols() == num_referenced_vars);
    }
    virtual ~LinearEqualityConstraintImpl() {}

    const Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> & getMatrix() const override { return A; }
    const Eigen::Matrix<double,Eigen::Dynamic,1>& getVector() const override { return b; }

    /* updateConstraint
     * @brief change the parameters of the constraint (A and b), but not the variable associations
     *
     * note that A and b can change size in the rows only (representing a different number of linear constraints, but on the same decision variables)
     */
    template <typename DerivedA,typename DerivedB>
    void updateConstraint(const Eigen::MatrixBase<DerivedA>& Aeq, const Eigen::MatrixBase<DerivedB>& beq)
    {
      assert(Aeq.rows()==beq.rows());
      if (Aeq.cols() != A.cols()) throw std::runtime_error("Can't change the number of decision variables");
      A.conservativeResize(Aeq.rows(),Eigen::NoChange);
      A = Aeq;
      b.conservativeResize(beq.rows());
      b = beq;
    };

  private:
    Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> A;
    Eigen::Matrix<double,Eigen::Dynamic,1> b;
  };


  class OptimizationProblem {
  public:
    OptimizationProblem() : problem_type(new LeastSquares), num_vars(0) {};

    const DecisionVariableView addContinuousVariables(std::size_t num_new_vars, std::string name = "x") {
      DecisionVariable v;
      v.type = DecisionVariable::CONTINUOUS;
      v.name = name;
      v.data = Eigen::VectorXd::Zero(num_new_vars);
      v.start_index = num_vars;
      variables.push_back(v);
      num_vars += num_new_vars;

      return DecisionVariableView(variables.back());
    }
//    const DecisionVariable& addIntegerVariables(size_t num_new_vars, std::string name);
//  ...

    /** addConstraint
     * @brief adds a constraint to the program.  method specializations ensure that the constraint gets added in the right way
     */
//    void addConstraint(const std::shared_ptr<LinearConstraint>& con, const VariableList& vars) {}
<commit_msg>add bounding box constraint<commit_after>#ifndef DRAKE_OPTIMIZATION_H
#define DRAKE_OPTIMIZATION_H

#include "Core.h"
#include <list>
#include <memory>
#include <initializer_list>

namespace Drake {

  class DecisionVariable {
    enum VarType {
      CONTINUOUS,
      INTEGER,
      BINARY
    };

    /** index()
     * @brief returns the first index of this variable in the entire variable vector for the program
     */
    size_t index() const { return start_index; }
    /** size()
     * @brief returns the number of elements in the decision variable vector
     */
    size_t size() const { return data.size(); }
    /** value()
     * @brief returns the actual stored value; which is only meaningful after calling solve() in the program.
     */
    const Eigen::VectorXd& value() const { return data; }

    VarType type;
    std::string name;     // todo: make this a vector of strings

    friend class OptimizationProblem;
    friend class DecisionVariableView;

  private:
    Eigen::VectorXd data;
    size_t start_index;
  };
  class DecisionVariableView {  // enables users to access pieces of the decision variables like they would any other eigen vector
  public:
    DecisionVariableView(const DecisionVariable& var) : var(var), start_index(0), length(var.data.rows()) {}
    DecisionVariableView(const DecisionVariable& var, size_t start, size_t n) : var(var), start_index(start), length(n) {
      assert(start+n<var.data.rows());
    }

    /** index()
     * @brief returns the first index of this variable in the entire variable vector for the program
     */
    size_t index() const { return var.start_index + start_index; }
    /** size()
     * @brief returns the number of elements in the decision variable vector
     */
    size_t size() const { return length; }
    /** value()
     * @brief returns the actual stored value; which is only meaningful after calling solve() in the program.
     */
    Eigen::VectorBlock<const Eigen::VectorXd,-1> value() const { return var.data.segment(start_index,length); }

    const DecisionVariableView operator()(size_t i) const { assert(i<=length); return DecisionVariableView(var,start_index+i,1);}
    const DecisionVariableView row(size_t i) const { assert(i<=length); return DecisionVariableView(var,start_index+i,1); }
    const DecisionVariableView head(size_t n) const { assert(n<=length); return DecisionVariableView(var,start_index,n); }
    const DecisionVariableView tail(size_t n) const { assert(n<=length); return DecisionVariableView(var,start_index+length-n,n); }
    const DecisionVariableView segment(size_t start, size_t n) const { assert(start+n<=length); return DecisionVariableView(var,start_index+start,n); }

    friend class OptimizationProblem;

  private:
    const DecisionVariable& var;
    size_t start_index, length;
  };

  typedef std::list<DecisionVariableView> VariableList;
  size_t size(const VariableList& var_list) {
    size_t s = 0;
    for (const auto& var : var_list) s+= var.size();
    return s;
  }

  // Quick notes about this design:
  // need to have lists of constraints (if not functions), so I want a (non-templated) base class.
  // would be nice to have templated types for specialized functions.  Not strictly required.
  // approach: let functions be templated, and use lambda closures/std::function to wrap them into the constraint classes.

  /**
   * @defgroup function_concept Function Concept
   * @ingroup concepts
   * @{
   * @brief Describes a mapping from one Vector to another Vector y = f(x)
   *
   * @nbsp
   *
   * | Every model of this concept must implement |  |
   * ---------------------|------------------------------------------------------------|
   * | X::InputVector     | type for the input to the system, which models the Vector<ScalarType> concept |
   * | X::OutputVector    | type for the output from the system, which models the Vector<ScalarType> concept |
   * | template <ScalarType> OutputVector<ScalarType> operator()(const InputVector<ScalarType>& x) | the actual function |
   * | InputOutputRelation getProperties() | |
   * | size_t getNumInputs() | only required if the input vector is dynamically-sized |
   * | size_t getNumOutputs() | only required if the output vector is dynamically-sized |
   *
   * (always try to label your methods with const if possible)
   *
   * @}
   */

  /*
   * some thoughts: a constraint is a function + lower and upper bounds.  it should support evaluating the constraint, adding it to an optimization problem,
   * and have support for constraints that require slack variables (adding additional decision variables to the problem).  There
   * should also be some notion of parameterized constraints:  e.g. the acceleration constraints in the rigid body dynamics are constraints
   * on vdot and f, but are "parameterized" by q and v.
   */
  class Constraint {
  public:
    Constraint(const VariableList& vars) : variable_list(vars), lower_bound(size(vars)), upper_bound(size(vars)) {
      lower_bound.setConstant(-std::numeric_limits<double>::infinity());
      upper_bound.setConstant(std::numeric_limits<double>::infinity());
    }

    template <typename DerivedLB, typename DerivedUB>
    Constraint(const VariableList& vars, const Eigen::MatrixBase<DerivedLB>& lb, const Eigen::MatrixBase<DerivedUB>& ub) : variable_list(vars), lower_bound(lb), upper_bound(ub)
    {
      assert(size(vars) == size(lower_bound) && "Lower bound must have exactly one element for every variable");
      assert(size(vars) == size(upper_bound) && "Upper bound must have exaclty one element for every variable");
    }
    virtual ~Constraint() {}

    const VariableList& getVariableList() const { return variable_list; }
  protected:
    VariableList variable_list;
    Eigen::VectorXd lower_bound, upper_bound;
  };

  // DifferentiableConstraint, PolynomialConstraint, QuadraticConstraint, ComplementarityConstraint, IntegerConstraint, ...

  /** LinearEqualityConstraint
   * @brief Implements a constraint of the form @f Ax = b @f
   */
  class LinearEqualityConstraint : public Constraint {
  public:
    LinearEqualityConstraint(const VariableList& vars) : Constraint(vars) {}
    virtual ~LinearEqualityConstraint() {}

    virtual const Eigen::MatrixXd& getMatrix() const = 0;
    virtual const Eigen::VectorXd& getVector() const = 0;
  };

  class LinearEqualityConstraintImpl : public LinearEqualityConstraint {
  public:
    template <typename DerivedA,typename DerivedB>
    LinearEqualityConstraintImpl(const VariableList& vars, const Eigen::MatrixBase<DerivedA>& Aeq, const Eigen::MatrixBase<DerivedB>& beq)
            : A(Aeq), b(beq), LinearEqualityConstraint(vars) {
      assert(A.rows()==b.rows());
      // todo: only do this loop if debug mode (only used for assert)
      int num_referenced_vars = 0;
      for (const DecisionVariableView& v : vars) {
        num_referenced_vars += v.size();
      }
      assert(A.cols() == num_referenced_vars);
    }
    virtual ~LinearEqualityConstraintImpl() {}

    const Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> & getMatrix() const override { return A; }
    const Eigen::Matrix<double,Eigen::Dynamic,1>& getVector() const override { return b; }

    /* updateConstraint
     * @brief change the parameters of the constraint (A and b), but not the variable associations
     *
     * note that A and b can change size in the rows only (representing a different number of linear constraints, but on the same decision variables)
     */
    template <typename DerivedA,typename DerivedB>
    void updateConstraint(const Eigen::MatrixBase<DerivedA>& Aeq, const Eigen::MatrixBase<DerivedB>& beq)
    {
      assert(Aeq.rows()==beq.rows());
      if (Aeq.cols() != A.cols()) throw std::runtime_error("Can't change the number of decision variables");
      A.conservativeResize(Aeq.rows(),Eigen::NoChange);
      A = Aeq;
      b.conservativeResize(beq.rows());
      b = beq;
    };

  private:
    Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> A;
    Eigen::Matrix<double,Eigen::Dynamic,1> b;
  };

  /** BoundingBoxConstraint
 * @brief Implements a constraint of the form @f lb <= x <= ub @f
 * Note: the base Constraint class (as implemented at the moment) could play this role.  But this class enforces
 * that it is ONLY a bounding box constraint, and not something more general.
 */
  class BoundingBoxConstraint : public Constraint {  // todo: derive from LinearConstraint (when it exists)
  public:
    template <typename DerivedLB, typename DerivedUB>
    BoundingBoxConstraint(const VariableList& vars, const Eigen::MatrixBase<DerivedLB>& lb, const Eigen::MatrixBase<DerivedUB>& ub) : Constraint(vars,lb,ub) {}
    virtual ~BoundingBoxConstraint() {}
  };


  class OptimizationProblem {
  public:
    OptimizationProblem() : problem_type(new LeastSquares), num_vars(0) {};

    const DecisionVariableView addContinuousVariables(std::size_t num_new_vars, std::string name = "x") {
      DecisionVariable v;
      v.type = DecisionVariable::CONTINUOUS;
      v.name = name;
      v.data = Eigen::VectorXd::Zero(num_new_vars);
      v.start_index = num_vars;
      variables.push_back(v);
      num_vars += num_new_vars;

      return DecisionVariableView(variables.back());
    }
//    const DecisionVariable& addIntegerVariables(size_t num_new_vars, std::string name);
//  ...

    /** addConstraint
     * @brief adds a constraint to the program.  method specializations ensure that the constraint gets added in the right way
     */
//    void addConstraint(const std::shared_ptr<LinearConstraint>& con, const VariableList& vars) {}

{'fraction_non_alphanumeric': 0.11097972972972973, 'fraction_numerical': 0.0012387387387387387, 'mean_word_length': 3.6986772486772486, 'pattern_counts': {'":': 0, '<': 69, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6859644', 'n_tokens_mistral': 5122, 'n_tokens_neox': 4888, 'n_words': 1598}