Example #1
0
mwSize *mxGetDimensions(const mxArray *ptr)
{
    InternalType *pIT = (InternalType *)ptr;
    if (pIT == NULL)
    {
        return NULL;
    }

    switch (pIT->getType())
    {
        case InternalType::ScilabList:
        case InternalType::ScilabMList:
        case InternalType::ScilabTList:
        {
            int *piDims = (int *)MALLOC(sizeof(int));

            piDims[0] = pIT->getAs<Container>()->getSize();
            return piDims;
        }
        default:
        {
            GenericType *pGT = pIT->getAs<GenericType>();
            if (pGT == NULL)
            {
                return NULL;
            }
            return pGT->getDimsArray();
        }
    }
    return NULL;
}
Example #2
0
bool GenericType::operator!=(const GenericType& op2) const{
  if(isString() && op2.isString()){
    return toString().compare(op2.toString()) != 0;
  }

  if(isInt() && op2.isInt()){
    return toInt() != op2.toInt();
  }

  if(isDouble() && op2.isDouble()){
    return toDouble() != op2.toDouble();
  }

  if(isDoubleVector() && op2.isDoubleVector()){
    const vector<double> &v1 = toDoubleVector();
    const vector<double> &v2 = op2.toDoubleVector();
    if(v1.size() != v2.size()) return true;
    for(int i=0; i<v1.size(); ++i)
      if(v1[i] != v2[i]) return true;
    return false;
  }

  if(isIntVector() && op2.isIntVector()){
    const vector<int> &v1 = toIntVector();
    const vector<int> &v2 = op2.toIntVector();
    if(v1.size() != v2.size()) return true;
    for(int i=0; i<v1.size(); ++i)
      if(v1[i] != v2[i]) return true;
    return false;
  }
  
  // Different types
  return true;
}
Example #3
0
int mxGetN(const mxArray *ptr)
{
    InternalType * pIT = (InternalType *)ptr;
    if (pIT == NULL)
    {
        return 0;
    }

    GenericType * pGT = pIT->getAs<GenericType>();
    if (pGT == 0)
    {
        return 0;
    }
    return pGT->getCols();
}
Example #4
0
void mxSetN(mxArray *ptr, int N)
{
    InternalType * pIT = (InternalType *)ptr;
    if (pIT == NULL)
    {
        return;
    }

    GenericType * pGT = pIT->getAs<GenericType>();
    if (pGT == NULL)
    {
        return;
    }

    pGT->resize(pGT->getRows(), N);
}
Example #5
0
void mxSetM(mxArray *ptr, int M)
{
    InternalType *pIT = (InternalType *)ptr;
    if (pIT == NULL)
    {
        return;
    }

    GenericType *pGT = pIT->getAs<GenericType>();
    if (pGT == NULL)
    {
        return;
    }

    pGT->resize(M, pGT->getCols());
}
Example #6
0
int mxGetNumberOfElements(const mxArray *ptr)
{
    InternalType *pIT = (InternalType *)ptr;
    if (pIT == NULL)
    {
        return 0;
    }

    GenericType *pGT = dynamic_cast<GenericType *>(pIT);
    if (pGT == NULL)
    {
        return 0;
    }

    return pGT->getSize();
}
Example #7
0
int mxIsComplex(const mxArray *ptr)
{
    InternalType *pIT = (InternalType *)ptr;
    if (pIT == NULL)
    {
        return 0;
    }

    GenericType *pGT = pIT->getAs<GenericType>();
    if (pGT == NULL)
    {
        return 0;
    }

    return pGT->isComplex() ? 1 : 0;
}
Example #8
0
int mxGetNumberOfDimensions(const mxArray *ptr)
{
    InternalType *pIT = (InternalType *)ptr;
    if (pIT == NULL)
    {
        return 0;
    }

    GenericType *pGT = pIT->getAs<GenericType>();
    if (pGT == NULL)
    {
        //InternalType but not GenericType, so mono dimension type.
        return 1;
    }

    return pGT->getDims();
}
void OptionsFunctionalityNode::addOption(const string &name, const opt_type& type, const GenericType &def_val, const string& desc, const std::vector<GenericType> &allowed_vals, bool inherit){

  // If inheriting, check if the type matches
  if (inherit && allowed_options.find(name)!=allowed_options.end()) {
     casadi_assert_message(allowed_options[name] == type,
        "The option '" << name << "' was indicated to inherit, but the type definition of the ancestor '" <<
         GenericType::get_type_description(allowed_options[name]) << "' conflicts with the type definition here '" <<
         GenericType::get_type_description(type) << "'."
     );
  }
  
  defaults_[name] = def_val;
  allowed_options[name] = type;

  std::vector<GenericType> allowed_vals_vec;
  
  // Inherit allowed_vals
  if (inherit && allowed_vals_.find(name)!=allowed_vals_.end()) {
    allowed_vals_vec.insert( allowed_vals_vec.end(), allowed_vals_[name].begin(), allowed_vals_[name].end() );
  }
  // Insert current allowed_vals
  allowed_vals_vec.insert( allowed_vals_vec.end(), allowed_vals.begin(), allowed_vals.end() );
  
  if(!def_val.isNull())
    dictionary_[name] = def_val;

  // Inherit description
  std::stringstream s;
  if (inherit && description_.find(name)!=description_.end()) {
    s << description_[name];
    if (!desc.empty())
      s << std::endl;
  }
  // Insert current description
  s << desc;
  description_[name] = s.str();

  allowed_vals_[name] = allowed_vals_vec;

}
Example #10
0
int getOptionals(void* _pvCtx, char* pstFuncName, rhs_opts opts[])
{
    GatewayStruct* pStr = (GatewayStruct*)_pvCtx;
    types::optional_list opt = *pStr->m_pOpt;
    int i = 0;

    /* reset first field since opts is declared static in calling function */

    while (opts[i].pstName != NULL)
    {
        opts[i].iPos = -1;
        i++;
    }

    for (i = 0 ; i < opt.size() ; i++)
    {
        int typeOfOpt = -1;
        char* pstOpts = wide_string_to_UTF8(opt[i].first.c_str());
        int index = findOptional(_pvCtx, pstOpts, opts);
        FREE(pstOpts);

        if (index < 0)
        {
            sciprint(_("%ls: Unrecognized optional arguments %ls.\n"), pStr->m_pstName, opt[i].first.c_str());
            printOptionalNames(_pvCtx, opts);
            return 0;
        }

        opts[index].iPos = i + 1;
        GenericType* pGT = (GenericType*)opt[i].second;
        getVarType(_pvCtx, (int*)pGT, &typeOfOpt);
        opts[index].iType = typeOfOpt;

        if (typeOfOpt == sci_implicit_poly)
        {
            InternalType* pIT = NULL;
            ImplicitList* pIL = pGT->getAs<ImplicitList>();
            pIT = pIL->extractFullMatrix();
            Double* impResult = (Double*)pIT;
            opts[index].iRows = impResult->getRows();
            opts[index].iCols = impResult->getCols();
            opts[index].piAddr = (int*)impResult;
            opts[index].iType = sci_matrix;
        }
        else
        {
            opts[index].iRows = pGT->getRows();
            opts[index].iCols = pGT->getCols();
            opts[index].piAddr = (int*)pGT;
        }
    }
    //   int index = -1;
    //GatewayStruct* pStr = (GatewayStruct*)_pvCtx;

    //   wchar_t* pwstProperty = to_wide_string(pstProperty);

    //   for(int i = 0 ; i < pStr->m_pOpt->size() ; i++)
    //   {
    //       std::pair<std::wstring, InternalType*> current = (*pStr->m_pOpt)[i];
    //       if(wcscmp(current.first.c_str(), pwstProperty) == 0)
    //       {
    //           index = i;
    //           break;
    //       }
    //   }

    //   FREE(pwstProperty);

    return 1;
}
void OptionsFunctionalityNode::setOption(const string &name, const GenericType &op) {
  assert_exists(name);

  // If we have an empty vector, than we are not strict about the type
  if (op.isEmptyVector()) {
    dictionary_[name] = GenericType::from_type(allowed_options[name]);
    return;
  }

  // Some typechecking
  if (!op.can_cast_to(allowed_options[name]) && !op.isNull()) {
    stringstream ss;
    ss << "Option '" << name << "' expects a '" <<
        GenericType::get_type_description(allowed_options[name]) << "' type." << endl;
    if (op.getType() == OT_BOOLEAN) {
      ss << "You supplied another type, possibly boolean." << endl;
      if (allowed_options[name]==OT_REAL || allowed_options[name]==OT_INTEGER) {
        ss << "(A common mistake is to use SX/MX instead of floats/DMatrix in this context)"
           << endl;
      }
    } else {
      ss << "You supplied a type '" << op.get_description() << "' instead." << endl;
    }
    if (!allowed_vals_[name].empty()) {
      ss << "(Allowed values are:";
      for (std::vector<GenericType>::const_iterator it=allowed_vals_[name].begin();
           it!=allowed_vals_[name].end();it++) {
        ss << " '" << *it << "'";
      }
      ss << ")" << endl;
    }
    casadi_error(ss.str());
  }

  // If allowed values are listed, check them.
  if (!allowed_vals_[name].empty()) {
    bool found;
    GenericType problem = op;
    if (op.isStringVector()) {
      found = true;
      const std::vector<std::string> & opv = op.toStringVector();
      for (std::vector<std::string>::const_iterator it=opv.begin();it!=opv.end();it++) {
        std::cout << "checking " << *it << std::endl;
        if (std::find(allowed_vals_[name].begin(),
                      allowed_vals_[name].end(), (*it))==allowed_vals_[name].end()) {
          problem = (*it);
          found = false;
          break;
        }
      }
    } else {
      found = false;
      for (std::vector<GenericType>::const_iterator it=allowed_vals_[name].begin();
           it!=allowed_vals_[name].end();it++) {
       found = found || (*it) == op;
      }
    }
    // If supplied op is not in allowed values, raise an error.
    if (!found) {
      stringstream ss;
      ss << "Option '" << name << "' does not allow '" << problem  << "'." << endl;
      ss << "(Allowed values options are:";
      for (std::vector<GenericType>::const_iterator it=allowed_vals_[name].begin();
           it!=allowed_vals_[name].end();it++) {
        ss << " '" << *it << "'";
      }
      ss << ")" << endl;
      casadi_error(ss.str());
    }
  }
  // Save the option
  dictionary_[name] = op;
}
Example #12
0
bool getDimsFromArguments(types::typed_list& in, const std::string& _pstName, int* _iDims, int** _piDims, bool* _alloc)
{
    types::Double* pOut = 0;

    *_alloc = false;
    *_iDims = 0;
    *_piDims = NULL;

    if (in.size() == 0)
    {
        *_iDims = 2;
        *_piDims = new int[*_iDims];
        (*_piDims)[0] = 1;
        (*_piDims)[1] = 1;
        *_alloc = true;
        return true;
    }
    else if (in.size() == 1)
    {
        *_iDims = 1;
        // :
        if (in[0]->isColon())
        {
            *_iDims = -1;
            return false;
        }

        if (in[0]->isArrayOf() == false)
        {
            if (in[0]->isSparse())
            {
                Sparse* sp = in[0]->getAs<Sparse>();
                *_iDims = sp->getDims();
                *_piDims = sp->getDimsArray();
                return true;
            }
            else if (in[0]->isSparseBool())
            {
                SparseBool* sp = in[0]->getAs<SparseBool>();
                *_iDims = sp->getDims();
                *_piDims = sp->getDimsArray();
                return true;
            }
            return false;
        }

        GenericType* pIn = in[0]->getAs<GenericType>();
        *_iDims = pIn->getDims();
        *_piDims = pIn->getDimsArray();

        return true;
    }
    else
    {
        *_iDims = static_cast<int>(in.size());
        *_piDims = new int[*_iDims];
        *_alloc = true;
        for (int i = 0; i < *_iDims; i++)
        {
            if (in[i]->isArrayOf() == false)
            {
                delete[] * _piDims;
                Scierror(999, _("%s: Wrong type for input argument #%d: A scalar expected.\n"), _pstName.c_str(), i + 1);
                return false;
            }

            types::GenericType* pGTIn = in[i]->getAs<types::GenericType>();
            if (pGTIn->isScalar() == false || pGTIn->isComplex())
            {
                delete[] * _piDims;
                Scierror(999, _("%s: Wrong size for input argument #%d: A scalar expected.\n"), _pstName.c_str(), i + 1);
                return false;
            }

            switch (in[i]->getType())
            {
                case types::InternalType::ScilabDouble:
                {
                    double dValue = in[i]->getAs<types::Double>()->get(0);
                    if (dValue >= INT_MAX)
                    {
                        delete[] * _piDims;
                        Scierror(999, _("%s: variable size exceeded : less than %d expected.\n"), _pstName.c_str(), INT_MAX);
                        return false;
                    }
                    (*_piDims)[i] = static_cast<int>(dValue);
                }
                break;
                case types::InternalType::ScilabInt8:
                    (*_piDims)[i] = static_cast<int>(in[i]->getAs<types::Int8>()->get()[0]);
                    break;
                case types::InternalType::ScilabUInt8:
                    (*_piDims)[i] = static_cast<int>(in[i]->getAs<types::UInt8>()->get()[0]);
                    break;
                case types::InternalType::ScilabInt16:
                    (*_piDims)[i] = static_cast<int>(in[i]->getAs<types::Int16>()->get()[0]);
                    break;
                case types::InternalType::ScilabUInt16:
                    (*_piDims)[i] = static_cast<int>(in[i]->getAs<types::UInt16>()->get()[0]);
                    break;
                case types::InternalType::ScilabInt32:
                    (*_piDims)[i] = in[i]->getAs<types::Int32>()->get()[0];
                    break;
                case types::InternalType::ScilabUInt32:
                    (*_piDims)[i] = static_cast<int>(in[i]->getAs<types::UInt32>()->get()[0]);
                    break;
                case types::InternalType::ScilabInt64:
                {
                    long long llValue = in[i]->getAs<types::Int64>()->get(0);
                    if (llValue >= INT_MAX)
                    {
                        delete[] * _piDims;
                        Scierror(999, _("%s: variable size exceeded : less than %d expected.\n"), _pstName.c_str(), INT_MAX);
                        return false;
                    }
                    (*_piDims)[i] = static_cast<int>(llValue);
                    break;
                }
                case types::InternalType::ScilabUInt64:
                {
                    unsigned long long ullValue = in[i]->getAs<types::UInt64>()->get(0);
                    if (ullValue >= INT_MAX)
                    {
                        delete[] * _piDims;
                        Scierror(999, _("%s: variable size exceeded : less than %d expected.\n"), _pstName.c_str(), INT_MAX);
                        return false;
                    }
                    (*_piDims)[i] = static_cast<int>(ullValue);
                    break;
                }
                default:
                    Scierror(999, _("%s: Wrong size for input argument #%d: A scalar expected.\n"), _pstName.c_str(), i + 1);
                    return false;
            }
        }

        return true;
    }

    return false;
}
Example #13
0
void AcadoOCPInternal::evaluate(int nfdir, int nadir){ 
  // Initial constraint function
  if(!rfcn_.f_.isNull()){
    const Matrix<double>& lbr = input(ACADO_LBR);
    ACADO::Vector lb(lbr.size(),&lbr.front());
    const Matrix<double>& ubr = input(ACADO_UBR);
    ACADO::Vector ub(ubr.size(),&ubr.front());
    ocp_->subjectTo( ACADO::AT_START, lb <= (*rfcn_.fcn_)(*arg_) <= ub);
  }

  // Path constraint function
  if(!cfcn_.f_.isNull()){
    const Matrix<double>& lbc = input(ACADO_LBC);
    ACADO::Vector lb(lbc.size(),&lbc.front());
    const Matrix<double>& ubc = input(ACADO_UBC);
    ACADO::Vector ub(ubc.size(),&ubc.front());
    ocp_->subjectTo( lb <= (*cfcn_.fcn_)(*arg_) <=  ub );
  }

  // State bounds
  Matrix<double> &lbx = input(ACADO_LBX);
  Matrix<double> &ubx = input(ACADO_UBX);
  for(int i=0; i<nxd_; ++i)
    ocp_->subjectTo( lbx.at(i) <= xd_[i] <=  ubx.at(i) );
  for(int i=nxd_; i<nx_; ++i)
    ocp_->subjectTo( lbx.at(i) <= xa_[i-nxd_] <=  ubx.at(i) );

  // Pass bounds on state at initial time
  Matrix<double> &lbx0 = input(ACADO_LBX0);
  Matrix<double> &ubx0 = input(ACADO_UBX0);
  for(int i=0; i<nxd_; ++i)
    ocp_->subjectTo( ACADO::AT_START, lbx0.at(i) <= xd_[i] <=  ubx0.at(i) );
  for(int i=nxd_; i<nx_; ++i)
    ocp_->subjectTo( ACADO::AT_START, lbx0.at(i) <= xa_[i-nxd_] <=  ubx0.at(i) );

//     ocp_->subjectTo( AT_END  , xd_[1] ==  0.0 );
//     ocp_->subjectTo( AT_END  , xd_[2] ==  0.0 );

  // Control bounds
  Matrix<double> &lbu = input(ACADO_LBU);
  Matrix<double> &ubu = input(ACADO_UBU);
  for(int i=0; i<nu_; ++i)
    ocp_->subjectTo( lbu.at(i) <= u_[i] <= ubu.at(i) );

  // Parameter bounds
  Matrix<double> &lbp = input(ACADO_LBP);
  Matrix<double> &ubp = input(ACADO_UBP);
  for(int i=0; i<np_; ++i)
    ocp_->subjectTo( lbp.at(i) <= p_[i] <= ubp.at(i) );

  // Periodic boundary condition
  if(hasSetOption("periodic_bounds")){
    const vector<int>& periodic = getOption("periodic_bounds");
    if(periodic.size()!=nx_) throw CasadiException("wrong dimension for periodic_bounds");
    for(int i=0; i<nxd_; ++i)
      if(periodic[i])
        ocp_->subjectTo( 0.0, xd_[i], -xd_[i], 0.0);

    for(int i=nxd_; i<nx_; ++i)
      if(periodic[i])
        ocp_->subjectTo( 0.0, xa_[i-nxd_], -xa_[i-nxd_], 0.0);
  }
  
  algorithm_ = new ACADO::OptimizationAlgorithm(*ocp_);
  
  // set print level
  ACADO::PrintLevel printlevel;
  if(getOption("print_level")=="none")        printlevel = ACADO::NONE;
  else if(getOption("print_level")=="low")    printlevel = ACADO::LOW;
  else if(getOption("print_level")=="medium") printlevel = ACADO::MEDIUM;
  else if(getOption("print_level")=="high")   printlevel = ACADO::HIGH;
  else if(getOption("print_level")=="debug")  printlevel = ACADO::DEBUG;
  else throw CasadiException("Illegal print level. Allowed are \"none\", \"low\", \"medium\", \"high\", \"debug\"");
  algorithm_->set(ACADO::INTEGRATOR_PRINTLEVEL, printlevel );

  // Set integrator
  if(hasSetOption("integrator")){
    GenericType integ = getOption("integrator");
    ACADO::IntegratorType itype;
    if(integ=="rk4")           itype=ACADO::INT_RK4;
    else if(integ=="rk12")     itype=ACADO::INT_RK12;
    else if(integ=="rk23")     itype=ACADO::INT_RK23;
    else if(integ=="rk45")     itype=ACADO::INT_RK45;
    else if(integ=="rk78")     itype=ACADO::INT_RK78;
    else if(integ=="bdf")      itype=ACADO::INT_BDF;
    else if(integ=="discrete") itype=ACADO::INT_DISCRETE;
    else if(integ=="unknown")  itype=ACADO::INT_UNKNOWN;
    #ifdef ACADO_HAS_USERDEF_INTEGRATOR
    else if(integ=="casadi"){
      if(ACADO::Integrator::integrator_creator_ || ACADO::Integrator::integrator_user_data_)
        throw CasadiException("AcadoOCPInternal::AcadoOCPInternal: An instance already exists");
      
      if(integrators_.size() <= n_nodes_)
        throw CasadiException("AcadoOCPInternal::AcadoOCPInternal: Number of integrators does not match number of shooting nodes");
      
      ACADO::Integrator::integrator_creator_ = &AcadoIntegratorBackend::create;
      ACADO::Integrator::integrator_user_data_ = this;
      itype=ACADO::INT_UNKNOWN;
    }
    #endif
  else throw CasadiException("AcadoOCPInternal::evaluate: no such integrator: " + integ.toString());
    algorithm_->set(ACADO::INTEGRATOR_TYPE, itype);
  };
  
  // Set integrator tolerance
  if(hasSetOption("integrator_tolerance")) algorithm_->set( ACADO::INTEGRATOR_TOLERANCE, getOption("integrator_tolerance").toDouble());
  if(hasSetOption("absolute_tolerance")) algorithm_->set( ACADO::ABSOLUTE_TOLERANCE, getOption("absolute_tolerance").toDouble());
  if(hasSetOption("kkt_tolerance")) algorithm_->set( ACADO::KKT_TOLERANCE, getOption("kkt_tolerance").toDouble());
  if(hasSetOption("max_num_iterations")) algorithm_->set( ACADO::MAX_NUM_ITERATIONS, getOption("max_num_iterations").toInt() );
  if(hasSetOption("max_num_integrator_steps")) algorithm_->set( ACADO::MAX_NUM_INTEGRATOR_STEPS, getOption("max_num_integrator_steps").toInt() );
  if(hasSetOption("relaxation_parameter")) algorithm_->set( ACADO::RELAXATION_PARAMETER, getOption("relaxation_parameter").toDouble());
  
  if(hasSetOption("dynamic_sensitivity")){
    if(getOption("dynamic_sensitivity") == "forward_sensitivities")
      algorithm_->set( ACADO::DYNAMIC_SENSITIVITY,  ACADO::FORWARD_SENSITIVITY );
    else if(getOption("dynamic_sensitivity") == "backward_sensitivities")
      algorithm_->set( ACADO::DYNAMIC_SENSITIVITY,  ACADO::BACKWARD_SENSITIVITY );
    else 
      throw CasadiException("illegal dynamic_sensitivity");
  }

  if(hasSetOption("hessian_approximation")){
    int hess;
    GenericType op = getOption("hessian_approximation");
    if(op=="exact_hessian")                 hess = ACADO::EXACT_HESSIAN;
    else if(op == "constant_hessian")       hess = ACADO::CONSTANT_HESSIAN;
    else if(op == "full_bfgs_update")       hess = ACADO::FULL_BFGS_UPDATE;
    else if(op == "block_bfgs_update")      hess = ACADO::BLOCK_BFGS_UPDATE;
    else if(op == "gauss_newton")           hess = ACADO::GAUSS_NEWTON;
    else if(op == "gauss_newton_with_block_bfgs") hess = ACADO::GAUSS_NEWTON_WITH_BLOCK_BFGS;
    else throw CasadiException("illegal hessian approximation");
    
    algorithm_->set( ACADO::HESSIAN_APPROXIMATION,  hess);
  }

  // should the states be initialized by a forward integration?
  bool auto_init = getOption("auto_init").toInt();

  // Initialize differential states
  if(nxd_>0){
    // Initial guess
    Matrix<double> &x0 = input(ACADO_X_GUESS);
    
    // Assemble the variables grid
    ACADO::VariablesGrid xd(nxd_, n_nodes_+1);
    for(int i=0; i<n_nodes_+1; ++i){
      ACADO::Vector v(nxd_,&x0.at(i*nx_));
      xd.setVector(i,v);
    }
    
    // Pass to acado
    algorithm_->initializeDifferentialStates(xd,auto_init ? ACADO::BT_TRUE : ACADO::BT_FALSE);
  }
    
  // Initialize algebraic states
  if(nxa_>0){
    // Initial guess
    Matrix<double> &x0 = input(ACADO_X_GUESS);
    
    // Assemble the variables grid
    ACADO::VariablesGrid xa(nxa_, n_nodes_+1);
    for(int i=0; i<n_nodes_+1; ++i){
      ACADO::Vector v(nxa_,&x0.at(i*nx_+nxd_));
      xa.setVector(i,v);
    }
    
    // Pass to acado
    algorithm_->initializeAlgebraicStates(xa,auto_init ? ACADO::BT_TRUE : ACADO::BT_FALSE);
  }
    
  // Initialize controls
  if(nu_>0){
    // Initial guess
    Matrix<double> &u0 = input(ACADO_U_GUESS);
    
    // Assemble the variables grid
    ACADO::VariablesGrid u(nu_, n_nodes_+1);
    for(int i=0; i<n_nodes_+1; ++i){
      ACADO::Vector v(nu_,&u0.at(i*nu_));
      u.setVector(i,v);
    }
    
    // Pass to acado
    algorithm_->initializeControls(u);
  }
    
  // Initialize parameters
  if(np_>0){
    // Initial guess
    Matrix<double> &p0 = input(ACADO_P_GUESS);
    
    // Assemble the variables grid
    ACADO::VariablesGrid p(np_, n_nodes_+1);
    for(int i=0; i<n_nodes_+1; ++i){
      ACADO::Vector v(np_,&p0.front()); // NB!
      p.setVector(i,v);
    }
    
    // Pass to acado
    algorithm_->initializeParameters(p);
  }

  // Solve
  algorithm_->solve();

  // Get the optimal state trajectory
  if(nxd_>0){
    Matrix<double> &xopt = output(ACADO_X_OPT);
    ACADO::VariablesGrid xd;
    algorithm_->getDifferentialStates(xd);
    assert(xd.getNumPoints()==n_nodes_+1);
    for(int i=0; i<n_nodes_+1; ++i){
      // Copy to result
      ACADO::Vector v = xd.getVector(i);
      &xopt.at(i*nx_) << v;
    }
  }
  if(nxa_>0){
    Matrix<double> &xopt = output(ACADO_X_OPT);
    ACADO::VariablesGrid xa;
    algorithm_->getAlgebraicStates(xa);
    assert(xa.getNumPoints()==n_nodes_+1);
    for(int i=0; i<n_nodes_+1; ++i){
      // Copy to result
      ACADO::Vector v = xa.getVector(i);
      &xopt.at(i*nx_ + nxd_) << v;
    }
  }

  // Get the optimal control trajectory
  if(nu_>0){
    Matrix<double> &uopt = output(ACADO_U_OPT);
    ACADO::VariablesGrid u;
    algorithm_->getControls(u);
    assert(u.getNumPoints()==n_nodes_+1);
    for(int i=0; i<n_nodes_+1; ++i){
      // Copy to result
      ACADO::Vector v = u.getVector(i);
      &uopt.at(i*nu_) << v;
    }
  }

  // Get the optimal parameters
  if(np_>0){
    Matrix<double> &popt = output(ACADO_P_OPT);
    ACADO::Vector p;
    algorithm_->getParameters(p);
    &popt.front() << p;
  }
  
  // Get the optimal cost
  double cost = algorithm_->getObjectiveValue();
  output(ACADO_COST).set(cost);
}
Example #14
0
/**
** toString to display Structs
** FIXME : Find a better indentation process
*/
bool Cell::subMatrixToString(std::wostringstream& ostr, int* _piDims, int /*_iDims*/)
{
    int iPrecision = ConfigVariable::getFormatSize();

    if (isEmpty())
    {
        ostr << L"   {}";
    }
    else
    {
        //max len for each column
        int *piTypeLen = new int[getCols()];
        int *piSizeLen = new int[getCols()];

        memset(piTypeLen, 0x00, getCols() * sizeof(int));
        memset(piSizeLen, 0x00, getCols() * sizeof(int));

        for (int j = 0 ; j < getCols() ; j++)
        {
            for (int i = 0 ; i < getRows() ; i++)
            {
                _piDims[0] = i;
                _piDims[1] = j;

                int iPos = getIndex(_piDims);
                InternalType* pIT = get(iPos);

                if (pIT->isAssignable())
                {
                    //compute number of digits to write dimensions
                    int iTypeLen = 0;
                    if (pIT->isGenericType())
                    {
                        GenericType* pGT = pIT->getAs<GenericType>();
                        for (int k = 0 ; k < pGT->getDims() ; k++)
                        {
                            iTypeLen += static_cast<int>(log10(static_cast<double>(pGT->getDimsArray()[k])) + 1);
                        }
                        piSizeLen[j] = std::max(piSizeLen[j], iTypeLen + (pGT->getDims() - 1));//add number of "x"
                    }
                    else
                    {
                        //types non derived from ArrayOf.
                        int iSize = static_cast<int>(log10(static_cast<double>(pIT->getAs<GenericType>()->getRows())) + 1);
                        piSizeLen[j] = std::max(piSizeLen[j], iSize);
                    }
                }
                else
                {
                    //no size so let a white space, size == 1
                    piSizeLen[j] = std::max(piSizeLen[j], 1);
                }

                piTypeLen[j] = std::max(piTypeLen[j], static_cast<int>(pIT->getTypeStr().size()));
            }
        }

        for (int i = 0 ; i < getRows() ; i++)
        {
            for (int j = 0 ; j < getCols() ; j++)
            {
                _piDims[0] = i;
                _piDims[1] = j;
                int iPos = getIndex(_piDims);
                InternalType* pIT = get(iPos);

                ostr << L"  [";
                if (pIT->isAssignable())
                {
                    if (pIT->isGenericType())
                    {
                        //"  ixjxkxl type   "
                        GenericType* pGT = pIT->getAs<GenericType>();
                        std::wostringstream ostemp;
                        for (int k = 0 ; k < pGT->getDims() ; k++)
                        {
                            if (k != 0)
                            {
                                ostemp << L"x";
                            }
                            ostemp << pGT->getDimsArray()[k];
                        }
                        configureStream(&ostr, piSizeLen[j], iPrecision, ' ');
                        ostr << std::right << ostemp.str();
                    }
                    else
                    {
                        //" i   "
                        configureStream(&ostr, piSizeLen[j], iPrecision, ' ');
                        if (pIT->isList())
                        {
                            ostr << std::right << pIT->getAs<List>()->getSize();
                        }
                        else
                        {
                            ostr << std::right << 1;
                        }
                    }
                }
                else
                {
                    configureStream(&ostr, piSizeLen[j], iPrecision, ' ');
                    ostr << L"";//fill with space
                }
                ostr << L" ";
                configureStream(&ostr, piTypeLen[j], iPrecision, ' ');
                ostr << std::left << pIT->getTypeStr();
                ostr << L"]";
            }
            ostr << std::endl;
        }

        delete[] piSizeLen;
        delete[] piTypeLen;
    }
    ostr << std::endl;
    return true;
}
Example #15
0
  void IpoptInternal::init(){
    // Free existing IPOPT instance
    freeIpopt();

    // Call the init method of the base class
    NLPSolverInternal::init();
    
    // Read user options
    exact_hessian_ = !hasSetOption("hessian_approximation") || getOption("hessian_approximation")=="exact";
#ifdef WITH_SIPOPT
    if(hasSetOption("run_sens")){
      run_sens_ = getOption("run_sens")=="yes";
    } else {
      run_sens_  = false;
    }
    if(hasSetOption("compute_red_hessian")){
      compute_red_hessian_ = getOption("compute_red_hessian")=="yes";
    } else {
      compute_red_hessian_ = false;
    }
#endif // WITH_SIPOPT

    // Get/generate required functions
    gradF();
    jacG();
    if(exact_hessian_){
      hessLag();
    }
  
    // Start an IPOPT application
    Ipopt::SmartPtr<Ipopt::IpoptApplication> *app = new Ipopt::SmartPtr<Ipopt::IpoptApplication>();
    app_ = static_cast<void*>(app);
    *app = new Ipopt::IpoptApplication();
  
#ifdef WITH_SIPOPT
    if(run_sens_ || compute_red_hessian_){
      // Start an sIPOPT application
      Ipopt::SmartPtr<Ipopt::SensApplication> *app_sens = new Ipopt::SmartPtr<Ipopt::SensApplication>();
      app_sens_ = static_cast<void*>(app_sens);
      *app_sens = new Ipopt::SensApplication((*app)->Jnlst(),(*app)->Options(),(*app)->RegOptions());
    
      // Register sIPOPT options
      Ipopt::RegisterOptions_sIPOPT((*app)->RegOptions());
      (*app)->Options()->SetRegisteredOptions((*app)->RegOptions());
    }
#endif // WITH_SIPOPT
  
    // Create an Ipopt user class -- need to use Ipopts spart pointer class
    Ipopt::SmartPtr<Ipopt::TNLP> *userclass = new Ipopt::SmartPtr<Ipopt::TNLP>();
    userclass_ = static_cast<void*>(userclass);
    *userclass = new IpoptUserClass(this);
    
    if(verbose_){
      cout << "There are " << nx_ << " variables and " << ng_ << " constraints." << endl;
      if(exact_hessian_) cout << "Using exact Hessian" << endl;
      else             cout << "Using limited memory Hessian approximation" << endl;
    }
 
    bool ret = true;
       
    // Pass all the options to ipopt
    for(map<string,opt_type>::const_iterator it=ops_.begin(); it!=ops_.end(); ++it)
      if(hasSetOption(it->first)){
        GenericType op = getOption(it->first);
        switch(it->second){
        case OT_REAL:
          ret &= (*app)->Options()->SetNumericValue(it->first,op.toDouble(),false);
          break;
        case OT_INTEGER:
          ret &= (*app)->Options()->SetIntegerValue(it->first,op.toInt(),false);
          break;
        case OT_STRING:
          ret &= (*app)->Options()->SetStringValue(it->first,op.toString(),false);
          break;
        default:
          throw CasadiException("Illegal type");
        }
      }
  
    if (!ret) casadi_error("IpoptInternal::Init: Invalid options were detected by Ipopt.");
  
    // Extra initialization required by sIPOPT
    //   #ifdef WITH_SIPOPT
    //   if(run_sens_ || compute_red_hessian_){
    //     Ipopt::ApplicationReturnStatus status = (*app)->Initialize("");
    //     casadi_assert_message(status == Solve_Succeeded, "Error during IPOPT initialization");
    //   }
    //   #endif // WITH_SIPOPT
  
    // Intialize the IpoptApplication and process the options
    Ipopt::ApplicationReturnStatus status = (*app)->Initialize();
    casadi_assert_message(status == Solve_Succeeded, "Error during IPOPT initialization");
  
#ifdef WITH_SIPOPT
    if(run_sens_ || compute_red_hessian_){
      Ipopt::SmartPtr<Ipopt::SensApplication> *app_sens = static_cast<Ipopt::SmartPtr<Ipopt::SensApplication> *>(app_sens_);
      (*app_sens)->Initialize();
    }
#endif // WITH_SIPOPT
  }