void ParallelizerInternal::evaluate(int nfdir, int nadir){
  // Let the first call (which may contain memory allocations) be serial when using OpenMP
  if(mode_== SERIAL || (first_call_ && mode_ == OPENMP)){
    for(int task=0; task<funcs_.size(); ++task){
      evaluateTask(task,nfdir,nadir);
    }
  } else if(mode_== OPENMP) {
    #ifdef WITH_OPENMP
    // Allocate some lists to collect statistics
    std::vector<int> task_allocation(funcs_.size());
    std::vector<int> task_order(funcs_.size());
    std::vector<double> task_cputime(funcs_.size());
    std::vector<double> task_starttime(funcs_.size());
    std::vector<double> task_endtime(funcs_.size());
    // A private counter
    int cnt=0;
    #pragma omp parallel for firstprivate(cnt)
    for(int task=0; task<funcs_.size(); ++task) {
      if (gather_stats_ && task==0) {
        stats_["max_threads"] = omp_get_max_threads();
        stats_["num_threads"] = omp_get_num_threads();
      }
      task_allocation[task] = omp_get_thread_num();
      task_starttime[task] = omp_get_wtime();
      
      // Do the actual work
      evaluateTask(task,nfdir,nadir);
      
      task_endtime[task] = omp_get_wtime();
      task_cputime[task] =  task_endtime[task] - task_starttime[task];
      task_order[task] = cnt++;
    }
    if (gather_stats_) {
      stats_["task_allocation"] = task_allocation;
      stats_["task_order"] = task_order;
      stats_["task_cputime"] = task_cputime;
    }
    // Measure all times relative to the earliest start_time.
    double start = *std::min_element(task_starttime.begin(),task_starttime.end());
    for (int task=0; task<funcs_.size(); ++task) {
      task_starttime[task] =  task_starttime[task] - start;
      task_endtime[task] = task_endtime[task] - start;
    }
    if (gather_stats_) {
      stats_["task_starttime"] = task_starttime;
      stats_["task_endtime"] = task_endtime;
    }
    
    #endif //WITH_OPENMP
    #ifndef WITH_OPENMP
      casadi_error("ParallelizerInternal::evaluate: OPENMP support was not available during CasADi compilation");
    #endif //WITH_OPENMP
  } else if(mode_ == MPI){
    casadi_error("ParallelizerInternal::evaluate: MPI not implemented");
  }
  first_call_ = false;
}
Example #2
0
  void ShellCompiler::init() {
    // Initialize the base classes
    CompilerInternal::init();

    // Read options
    string compiler = getOption("compiler").toString();
    string compiler_setup = getOption("compiler_setup").toString();
    vector<string> flags;
    if (hasSetOption("flags")) flags = getOption("flags");

    // Construct the compiler command
    stringstream cmd;
    cmd << compiler << " " << compiler_setup;
    for (vector<string>::const_iterator i=flags.begin(); i!=flags.end(); ++i) {
      cmd << " " << *i;
    }

    // C/C++ source file
    cmd << " " << name_;

    // Name of temporary file
#ifdef HAVE_MKSTEMPS
    // Preferred solution
    char bin_name[] = "tmp_casadi_compiler_shell_XXXXXX.so";
    if (mkstemps(bin_name, 3) == -1) {
      casadi_error("Failed to create a temporary file name");
    }
    bin_name_ = bin_name;
#else
    // Fallback, may result in deprecation warnings
    char* bin_name = tempnam(0, "tmp_casadi_compiler_shell_");
    bin_name_ = bin_name;
    free(bin_name);
#endif

    // Have relative paths start with ./
    if (bin_name_.at(0)!='/') {
      bin_name_ = "./" + bin_name_;
    }

    // Temporary file
    cmd << " -o " << bin_name_;

    // Compile into a shared library
    if (system(cmd.str().c_str())) {
      casadi_error("Compilation failed. Tried \"" + cmd.str() + "\"");
    }

    // Load shared library
    handle_ = dlopen(bin_name_.c_str(), RTLD_LAZY);
    casadi_assert_message(handle_!=0, "CommonExternal: Cannot open function: "
                          << bin_name_ << ". error code: "<< dlerror());
    // reset error
    dlerror();
  }
Example #3
0
  DMatrix IpoptInternal::getReducedHessian(){
#ifndef WITH_SIPOPT
    casadi_error("This feature requires sIPOPT support. Please consult the CasADi documentation.");
#else // WITH_SIPOPT
#ifndef WITH_CASADI_PATCH
    casadi_error("Retrieving the Hessian requires the CasADi sIPOPT patch. Please consult the CasADi documentation.");
#else // WITH_CASADI_PATCH
    return red_hess_;
#endif // WITH_SIPOPT
#endif // WITH_CASADI_PATCH

  }
Example #4
0
  DpleInternal::DpleInternal(const std::map<std::string, std::vector<Sparsity> > &st,
                             int nrhs, bool transp) :
    nrhs_(nrhs), transp_(transp) {

    // set default options
    setOption("name", "unnamed_dple_solver"); // name of the function

    addOption("const_dim", OT_BOOLEAN, true, "Assume constant dimension of P");
    addOption("pos_def", OT_BOOLEAN, false, "Assume P positive definite");

    addOption("error_unstable", OT_BOOLEAN, false,
              "Throw an exception when it is detected that Product(A_i, i=N..1) "
              "has eigenvalues greater than 1-eps_unstable");
    addOption("eps_unstable", OT_REAL, 1e-4, "A margin for unstability detection");

    st_.resize(Dple_STRUCT_NUM);
    for (std::map<std::string, std::vector<Sparsity> >::const_iterator i=st.begin();
         i!=st.end(); ++i) {
      if (i->first=="a") {
        st_[Dple_STRUCT_A]=i->second;
      } else if (i->first=="v") {
        st_[Dple_STRUCT_V]=i->second;
      } else {
        casadi_error("Unrecognized field in Dple structure: " << i->first);
      }
    }

    if (nrhs_==1) {
      ischeme_ = IOScheme(SCHEME_DPLEInput);
      oscheme_ = IOScheme(SCHEME_DPLEOutput);
    }
  }
Example #5
0
CRSSparsity sp_rowcol(std::vector<int> row, std::vector<int> col, int nrow, int ncol) {
  std::vector<int> rowind(nrow+1);
  std::vector<int> col_new(row.size()*col.size());
  
  // resulting col: the entries of col are repeated row.size() times
  for (int i=0;i<row.size();i++)
    std::copy(col.begin(),col.end(),col_new.begin()+col.size()*i);

  // resulting rowind: first entry is always zero
  int cnt=0;
  int z=0;
  rowind[0]=0;
  int k=0;
  try {
    for (k=0; k < row.size(); k++) {
      // resulting rowind: fill up rowind entries with copies
      while (z<row[k])
        rowind.at(++z)=cnt;
        
      // resulting rowind: add col.size() at each row[k]
      rowind.at(row[k]+1)=(cnt+=col.size());
    }
    while (z<nrow)
      rowind.at(++z)=cnt;                 
  }
  catch (out_of_range& oor) {
    casadi_error(
      "sp_rowcol: out-of-range error." << endl <<
      "The " << k << "th entry of row (" << row[k] << ") was bigger or equal to the specified total number of rows (" << nrow << ")"
    );
  }
  return CRSSparsity(nrow, ncol, col_new, rowind);
}
 bool QpoasesInterface::BooleanType_to_bool(qpOASES::BooleanType b) {
   switch (b) {
   case qpOASES::BT_TRUE:              return true;
   case qpOASES::BT_FALSE:             return false;
   default:                            casadi_error("not_implemented");
   }
 }
Example #7
0
std::vector<M> acadoIn(const std::string arg_s0="",M arg_m0=M(),const std::string arg_s1="",M arg_m1=M(),const std::string arg_s2="",M arg_m2=M(),const std::string arg_s3="",M arg_m3=M(),const std::string arg_s4="",M arg_m4=M(),const std::string arg_s5="",M arg_m5=M(),const std::string arg_s6="",M arg_m6=M(),const std::string arg_s7="",M arg_m7=M(),const std::string arg_s8="",M arg_m8=M(),const std::string arg_s9="",M arg_m9=M(),const std::string arg_s10="",M arg_m10=M(),const std::string arg_s11="",M arg_m11=M(),const std::string arg_s12="",M arg_m12=M(),const std::string arg_s13="",M arg_m13=M(),const std::string arg_s14="",M arg_m14=M(),const std::string arg_s15="",M arg_m15=M(),const std::string arg_s16="",M arg_m16=M()){
  std::vector<M> ret(17);
  std::map<std::string,M> arg;
  if (arg_s0!="") arg.insert(make_pair(arg_s0,arg_m0));
  if (arg_s1!="") arg.insert(make_pair(arg_s1,arg_m1));
  if (arg_s2!="") arg.insert(make_pair(arg_s2,arg_m2));
  if (arg_s3!="") arg.insert(make_pair(arg_s3,arg_m3));
  if (arg_s4!="") arg.insert(make_pair(arg_s4,arg_m4));
  if (arg_s5!="") arg.insert(make_pair(arg_s5,arg_m5));
  if (arg_s6!="") arg.insert(make_pair(arg_s6,arg_m6));
  if (arg_s7!="") arg.insert(make_pair(arg_s7,arg_m7));
  if (arg_s8!="") arg.insert(make_pair(arg_s8,arg_m8));
  if (arg_s9!="") arg.insert(make_pair(arg_s9,arg_m9));
  if (arg_s10!="") arg.insert(make_pair(arg_s10,arg_m10));
  if (arg_s11!="") arg.insert(make_pair(arg_s11,arg_m11));
  if (arg_s12!="") arg.insert(make_pair(arg_s12,arg_m12));
  if (arg_s13!="") arg.insert(make_pair(arg_s13,arg_m13));
  if (arg_s14!="") arg.insert(make_pair(arg_s14,arg_m14));
  if (arg_s15!="") arg.insert(make_pair(arg_s15,arg_m15));
  if (arg_s16!="") arg.insert(make_pair(arg_s16,arg_m16));
  typedef typename std::map<std::string,M>::const_iterator it_type;
  for(it_type it = arg.begin(); it != arg.end(); it++) {
    int n = getSchemeEntryEnum(SCHEME_ACADO_Input,it->first);
    if (n==-1)
      casadi_error("Keyword error in ACADO_Input: '" << it->first << "' is not recognized. Available keywords are: x_guess, u_guess, p_guess, lbx, ubx, lbx0, ubx0, lbxf, ubxf, lbu, ubu, lbp, ubp, lbc, ubc, lbr, ubr");
    ret[n] = it->second;
  }
  return ret;
}
GenericType OptionsFunctionalityNode::getOption(const string &name) const{

  // Locate the option
  Dictionary::const_iterator it = dictionary_.find(name);

  // Check if found
  if(it == dictionary_.end()){
    stringstream ss;
    if (allowed_options.find(name)!=allowed_options.end()) {
      ss << "Option: '" << name << "' has not been set." << endl;
      printOption(name,ss);
    } else {
      ss << "Option: '" << name << "' does not exist." << endl << endl;
      std::vector<std::string> suggestions;
      getBestMatches(name,suggestions,5);
      ss << "Did you mean one of the following?" << endl;
      for (int i=0;i<suggestions.size();++i)
        printOption(suggestions[i],ss);
      ss << "Use printOptions() to get a full list of options." << endl;
    }
    casadi_error(ss.str());
  }
  
  // Return the option
  return GenericType(it->second);
}
Example #9
0
  bool IpoptInternal::eval_grad_f(int n, const double* x, bool new_x, double* grad_f)
  {
    try {
      log("eval_grad_f started");
      double time1 = clock();
      casadi_assert(n == nx_);
    
      // Pass the argument to the function
      gradF_.setInput(x,NL_X);
      gradF_.setInput(input(NLP_SOLVER_P),NL_P);
      
      // Evaluate, adjoint mode
      gradF_.evaluate();
      
      // Get the result
      gradF_.output().getArray(grad_f,n,DENSE);
      
      // Printing
      if(monitored("eval_grad_f")){
        cout << "x = " << gradF_.input(NL_X) << endl;
        cout << "grad_f = " << gradF_.output() << endl;
      }

      if (regularity_check_ && !isRegular(gradF_.output().data())) casadi_error("IpoptInternal::grad_f: NaN or Inf detected.");
    
      double time2 = clock();
      t_eval_grad_f_ += double(time2-time1)/CLOCKS_PER_SEC;
      n_eval_grad_f_ += 1;
      log("eval_grad_f ok");
      return true;
    } catch (exception& ex){
      cerr << "eval_grad_f failed: " << ex.what() << endl;
      return false;
    }
  }
Example #10
0
  void Options::check(const Dict& opts) const {
    // Make sure all options exist and have the correct type
    for (auto&& op : opts) {
      const Options::Entry* entry = find(op.first);

      // Informative error message if option does not exist
      if (entry==nullptr) {
        stringstream ss;
        ss << "Unknown option: " << op.first << endl;
        ss << endl;
        ss << "Did you mean one of the following?" << endl;
        for (auto&& s : suggestions(op.first)) {
          print_one(s, ss);
        }
        ss << "Use print_options() to get a full list of options." << endl;
        casadi_error(ss.str());
      }

      // Check type
      casadi_assert(op.second.can_cast_to(entry->type),
                            "Illegal type for " + op.first + ": " +
                            op.second.get_description() +
                            " cannot be cast to " +
                            GenericType::get_type_description(entry->type) + ".");

    }
  }
Example #11
0
  SXElement Variable::atTime(double t, bool allocate) {
    // Find an existing element
    map<double, SXElement>::const_iterator it = timed_.find(t);

    // If not found
    if (it==timed_.end()) {
      if (allocate) {
        // Create a timed variable
        stringstream ss;
        ss << name() << ".atTime(" << t << ")";
        SXElement tvar = SXElement::sym(ss.str());

        // Save to map
        timed_[t] = tvar;

        // Return the expression
        return tvar;
      } else {
        casadi_error(" has no timed variable with t = " << t << ".");
      }

    } else {
      // Return the expression
      return it->second;
    }
  }
Example #12
0
  NlpSolver::NlpSolver(const std::string& name,
                       const std::string& solver,
                       const MXDict& nlp,
                       const Dict& opts) {
    // Create an NLP function
    MX x, p, f, g;
    for (MXDict::const_iterator i=nlp.begin(); i!=nlp.end(); ++i) {
      if (i->first=="x") {
        x = i->second;
      } else if (i->first=="p") {
        p = i->second;
      } else if (i->first=="f") {
        f = i->second;
      } else if (i->first=="g") {
        g = i->second;
      } else {
        casadi_error("No such field: \"" + i->first + "\"");
      }
    }
    MXFunction nlpf("nlp", nlpIn("x", x, "p", p), nlpOut("f", f, "g", g));

    // Create the solver instance
    assignNode(NlpSolverInternal::instantiatePlugin(solver, nlpf));
    setOption("name", name);
    setOption(opts);
    init();
  }
Example #13
0
  void LapackLuDense::prepare() {
    double time_start=0;
    if (CasadiOptions::profiling && CasadiOptions::profilingBinary) {
      time_start = getRealTime(); // Start timer
      profileWriteEntry(CasadiOptions::profilingLog, this);
    }
    prepared_ = false;

    // Get the elements of the matrix, dense format
    input(0).get(mat_);

    if (equilibriate_) {
      // Calculate the col and row scaling factors
      double colcnd, rowcnd; // ratio of the smallest to the largest col/row scaling factor
      double amax; // absolute value of the largest matrix element
      int info = -100;
      dgeequ_(&ncol_, &nrow_, getPtr(mat_), &ncol_, getPtr(r_),
              getPtr(c_), &colcnd, &rowcnd, &amax, &info);
      if (info < 0)
          throw CasadiException("LapackQrDense::prepare: "
                                "dgeequ_ failed to calculate the scaling factors");
      if (info>0) {
        stringstream ss;
        ss << "LapackLuDense::prepare: ";
        if (info<=ncol_)  ss << (info-1) << "-th row (zero-based) is exactly zero";
        else             ss << (info-1-ncol_) << "-th col (zero-based) is exactly zero";

        userOut() << "Warning: " << ss.str() << endl;



        if (allow_equilibration_failure_)  userOut() << "Warning: " << ss.str() << endl;
        else                              casadi_error(ss.str());
      }

      // Equilibrate the matrix if scaling was successful
      if (info!=0)
        dlaqge_(&ncol_, &nrow_, getPtr(mat_), &ncol_, getPtr(r_), getPtr(c_),
                &colcnd, &rowcnd, &amax, &equed_);
      else
        equed_ = 'N';
    }

    // Factorize the matrix
    int info = -100;
    dgetrf_(&ncol_, &ncol_, getPtr(mat_), &ncol_, getPtr(ipiv_), &info);
    if (info != 0) throw CasadiException("LapackLuDense::prepare: "
                                         "dgetrf_ failed to factorize the Jacobian");

    // Success if reached this point
    prepared_ = true;

    if (CasadiOptions::profiling && CasadiOptions::profilingBinary) {
      double time_stop = getRealTime(); // Stop timer
      profileWriteTime(CasadiOptions::profilingLog, this, 0, time_stop-time_start,
                       time_stop-time_start);
      profileWriteExit(CasadiOptions::profilingLog, this, time_stop-time_start);
    }
  }
Example #14
0
  void SXFunctionInternal::generateDeclarations(CodeGenerator& g) const {

    // Make sure that there are no free variables
    if (!free_vars_.empty()) {
      casadi_error("Code generation is not possible since variables "
                   << free_vars_ << " are free.");
    }
  }
Example #15
0
  void Assertion::eval(const double** arg, double** res, int* iw, double* w, int mem) const {
    if (arg[1][0]!=1) {
      casadi_error("Assertion error: " << fail_message_);
    }

    if (arg[0]!=res[0]) {
      copy(arg[0], arg[0]+nnz(), res[0]);
    }
  }
Example #16
0
 std::string QpoasesInterface::SubjectToStatus_to_string(qpOASES::SubjectToStatus b) {
   switch (b) {
   case qpOASES::ST_INACTIVE:          return "inactive";
   case qpOASES::ST_LOWER:             return "lower";
   case qpOASES::ST_INFEASIBLE_LOWER:  return "infeasible_lower";
   case qpOASES::ST_INFEASIBLE_UPPER:  return "infeasible_upper";
   case qpOASES::ST_UNDEFINED:         return "undefined";
   default:                            casadi_error("not_implemented");
   }
 }
Example #17
0
 std::string QpoasesInterface::PrintLevel_to_string(qpOASES::PrintLevel b) {
   switch (b) {
   case qpOASES::PL_TABULAR:           return "tabular";
   case qpOASES::PL_NONE:              return "none";
   case qpOASES::PL_LOW:               return "low";
   case qpOASES::PL_MEDIUM:            return "medium";
   case qpOASES::PL_HIGH:              return "high";
   default:                            casadi_error("not_implemented");
   }
 }
Example #18
0
 void IdasInterface::idas_error(const char* module, int flag) {
   // Successfull return or warning
   if (flag>=IDA_SUCCESS) return;
   // Construct error message
   stringstream ss;
   char* flagname = IDAGetReturnFlagName(flag);
   ss << module << " returned \"" << flagname << "\"."
      << " Consult IDAS documentation.";
   free(flagname);
   casadi_error(ss.str());
 }
Example #19
0
 std::vector<double> collocationPoints(int order, const std::string& scheme) {
   if (scheme=="radau") {
     casadi_assert_message(order>0 && order<10,"Error in collocationPoints(order, scheme): only order up to 9 supported for scheme 'radau', but got " << order << ".");
     return std::vector<double>(radau_points[order],radau_points[order]+order+1);
   } else if (scheme=="legendre") {
     casadi_assert_message(order>0 && order<10,"Error in collocationPoints(order, scheme): only order up to 9 supported for scheme 'legendre', but got " << order << ".");
     return std::vector<double>(legendre_points[order],legendre_points[order]+order+1);
   } else {
     casadi_error("Error in collocationPoints(order, scheme): unknown scheme '" << scheme << "'. Select one of 'radau', 'legendre'.");
   }
 }
Example #20
0
  bool IpoptInternal::eval_jac_g(int n, const double* x, bool new_x,int m, int nele_jac, int* iRow, int *jCol,double* values){
    try{
      log("eval_jac_g started");
    
      // Quich finish if no constraints
      if(m==0){
        log("eval_jac_g quick return (m==0)");
        return true;
      }
      
      // Get function
      Function& jacG = this->jacG();
    
      double time1 = clock();
      if (values == NULL) {
        int nz=0;
        const vector<int>& colind = jacG.output().colind();
        const vector<int>& row = jacG.output().row();
        for(int cc=0; cc<colind.size()-1; ++cc)
          for(int el=colind[cc]; el<colind[cc+1]; ++el){
            int rr = row[el];
            iRow[nz] = rr;
            jCol[nz] = cc;
            nz++;
          }
      } else {
        // Pass the argument to the function
        jacG.setInput(x,NL_X);
        jacG.setInput(input(NLP_SOLVER_P),NL_P);
      
        // Evaluate the function
        jacG.evaluate();

        // Get the output
        jacG.getOutput(values);
      
        if(monitored("eval_jac_g")){
          cout << "x = " << jacG.input(NL_X).data() << endl;
          cout << "J = " << endl;
          jacG.output().printSparse();
        }
        if (regularity_check_ && !isRegular(jacG.output().data())) casadi_error("IpoptInternal::jac_g: NaN or Inf detected.");
      }
    
      double time2 = clock();
      t_eval_jac_g_ += double(time2-time1)/CLOCKS_PER_SEC;
      n_eval_jac_g_ += 1;
      log("eval_jac_g ok");
      return true;
    } catch (exception& ex){
      cerr << "eval_jac_g failed: " << ex.what() << endl;
      return false;
    }
  }
Example #21
0
  void SXFunctionInternal::compileProgram(cl_program program) {
    // OpenCL return flag
    cl_int ret;

    ret = clBuildProgram(program, 1, &sparsity_propagation_kernel_.device_id, NULL, NULL, NULL);
    if (ret!=CL_SUCCESS) {
      const char* msg;
      switch (ret) {
      case CL_INVALID_PROGRAM: msg = "Program is not a valid program object."; break;
      case CL_INVALID_VALUE: msg = "(1) Device_list is NULL and num_devices is greater than zero, "
              "or device_list is not NULL and num_devices is zero. (2) pfn_notify "
              "is NULL but user_data is not NULL."; break;
      case CL_INVALID_DEVICE: msg = "OpenCL devices listed in device_list are not in the "
              "list of devices associated with program"; break;
      case CL_INVALID_BINARY: msg = "Program is created with clCreateWithProgramBinary and "
              "devices listed in device_list do not have a valid program binary loaded."; break;
      case CL_INVALID_BUILD_OPTIONS: msg = "The build options specified by options are invalid. ";
          break;
      case CL_INVALID_OPERATION: msg = "(1) The build of a program executable for any of the "
              "devices listed in device_list by a previous call to clBuildProgram for program "
              "has not completed. (2) There are kernel objects attached to program. "; break;
      case CL_COMPILER_NOT_AVAILABLE: msg = "Program is created with clCreateProgramWithSource "
              "and a compiler is not available i.e. CL_DEVICE_COMPILER_AVAILABLE specified "
              "in table 4.3 is set to CL_FALSE."; break;
      case CL_BUILD_PROGRAM_FAILURE: {
        msg = "There is a failure to build the program executable. This error will be "
            "returned if clBuildProgram does not return until the build has completed. ";

        // Determine the size of the log
        size_t log_size;
        clGetProgramBuildInfo(program, sparsity_propagation_kernel_.device_id,
                              CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);

        // Allocate memory for the log
        std::vector<char> log;
        log.resize(log_size);

        // Print the log
        clGetProgramBuildInfo(program, sparsity_propagation_kernel_.device_id,
                              CL_PROGRAM_BUILD_LOG, log_size, &(log[0]), NULL);
        userOut<true, PL_WARN>() << log << endl;
        break;
      }
      case CL_OUT_OF_RESOURCES: msg = "There is a failure to allocate resources required by the "
              "OpenCL implementation on the device."; break;
      case CL_OUT_OF_HOST_MEMORY: msg = "There is a failure to allocate resources required by "
              "the OpenCL implementation on the host."; break;
      default: msg = "Unknown error"; break;
      }

      casadi_error("clBuildProgram failed: " << msg);
    }
  }
Example #22
0
  void SqicInterface::sqic_error(const string& module, int flag) {
    // Find the error
    map<int, string>::const_iterator it = flagmap.find(flag);

    stringstream ss;
    if (it == flagmap.end()) {
      ss << "Unknown error (" << flag << ") from module \"" << module << "\".";
    } else {
      ss << "Module \"" << module << "\" returned flag \"" << it->second << "\".";
    }
    ss << " Consult SQIC documentation.";
    casadi_error(ss.str());
  }
Example #23
0
GenericType GenericType::from_type(opt_type type) {
  switch (type) {
      case OT_INTEGERVECTOR:
              return std::vector<int>();
      case OT_BOOLVECTOR:
              return std::vector<bool>();
      case OT_REALVECTOR:
              return std::vector<double>();
      case OT_STRINGVECTOR:
              return std::vector<std::string>();
      default:
              casadi_error("empty_from_type. Unsupported type " << type);
    }
}
Example #24
0
std::vector<M> mayerIn(const std::string arg_s0="",M arg_m0=M(),const std::string arg_s1="",M arg_m1=M()){
  std::vector<M> ret(2);
  std::map<std::string,M> arg;
  if (arg_s0!="") arg.insert(make_pair(arg_s0,arg_m0));
  if (arg_s1!="") arg.insert(make_pair(arg_s1,arg_m1));
  typedef typename std::map<std::string,M>::const_iterator it_type;
  for(it_type it = arg.begin(); it != arg.end(); it++) {
    int n = getSchemeEntryEnum(SCHEME_MayerInput,it->first);
    if (n==-1)
      casadi_error("Keyword error in MayerInput: '" << it->first << "' is not recognized. Available keywords are: x, p");
    ret[n] = it->second;
  }
  return ret;
}
Example #25
0
 qpOASES::PrintLevel QpoasesInterface::string_to_PrintLevel(std::string b) {
   if (b.compare("tabular")==0) {
     return qpOASES::PL_TABULAR;
   } else if (b.compare("none")==0) {
     return qpOASES::PL_NONE;
   } else if (b.compare("low")==0) {
     return qpOASES::PL_LOW;
   } else if (b.compare("medium")==0) {
     return qpOASES::PL_MEDIUM;
   } else if (b.compare("high")==0) {
     return qpOASES::PL_HIGH;
   } else {
     casadi_error("not_implemented");
   }
 }
Example #26
0
 Function Map::create(const std::string& parallelization, const Function& f, int n) {
   // Create instance of the right class
   string name = f.name() + "_" + to_string(n);
   Function ret;
   if (parallelization == "serial") {
     ret.assignNode(new Map(name, f, n));
   } else if (parallelization== "openmp") {
     ret.assignNode(new MapOmp(name, f, n));
   } else {
     casadi_error("Unknown parallelization: " + parallelization);
   }
   // Finalize creation
   ret->construct(Dict());
   return ret;
 }
Example #27
0
 qpOASES::SubjectToStatus QpoasesInterface::string_to_SubjectToStatus(std::string b) {
   if (b.compare("inactive")==0) {
     return qpOASES::ST_INACTIVE;
   } else if (b.compare("lower")==0) {
     return qpOASES::ST_LOWER;
   } else if (b.compare("infeasible_lower")==0) {
     return qpOASES::ST_INFEASIBLE_LOWER;
   } else if (b.compare("infeasible_upper")==0) {
     return qpOASES::ST_INFEASIBLE_UPPER;
   } else if (b.compare("undefined")==0) {
     return qpOASES::ST_UNDEFINED;
   } else {
     casadi_error("not_implemented");
   }
 }
void OptionsFunctionalityNode::assert_exists(const std::string &name) const {
  // First check if the option exists
  map<string, opt_type>::const_iterator it = allowed_options.find(name);
  if(it == allowed_options.end()){
    stringstream ss;
    ss << "Unknown option: " << name << endl;
    std::vector<std::string> suggestions;
    getBestMatches(name,suggestions,5);
    ss << endl;
    ss << "Did you mean one of the following?" << endl;
    for (int i=0;i<suggestions.size();++i)
      printOption(suggestions[i],ss);
    ss << "Use printOptions() to get a full list of options." << endl;
    casadi_error(ss.str());
  }
}
Example #29
0
std::vector<M> acadoOut(const std::string arg_s0="",M arg_m0=M(),const std::string arg_s1="",M arg_m1=M(),const std::string arg_s2="",M arg_m2=M(),const std::string arg_s3="",M arg_m3=M()){
  std::vector<M> ret(4);
  std::map<std::string,M> arg;
  if (arg_s0!="") arg.insert(make_pair(arg_s0,arg_m0));
  if (arg_s1!="") arg.insert(make_pair(arg_s1,arg_m1));
  if (arg_s2!="") arg.insert(make_pair(arg_s2,arg_m2));
  if (arg_s3!="") arg.insert(make_pair(arg_s3,arg_m3));
  typedef typename std::map<std::string,M>::const_iterator it_type;
  for(it_type it = arg.begin(); it != arg.end(); it++) {
    int n = getSchemeEntryEnum(SCHEME_ACADO_Output,it->first);
    if (n==-1)
      casadi_error("Keyword error in ACADO_Output: '" << it->first << "' is not recognized. Available keywords are: x_opt, u_opt, p_opt, cost");
    ret[n] = it->second;
  }
  return ret;
}
Example #30
0
  int IdasInterface::lsolveB(IDAMem IDA_mem, N_Vector b, N_Vector weight, N_Vector xzB,
                                    N_Vector xzdotB, N_Vector rrB) {
    try {
      auto m = to_mem(IDA_mem->ida_lmem);
      auto& s = m->self;
      IDAadjMem IDAADJ_mem;
      //IDABMem IDAB_mem;
      int flag;

      // Current time
      double t = IDA_mem->ida_tn; // TODO(Joel): is this correct?
      // Multiple of df_dydot to be added to the matrix
      double cj = IDA_mem->ida_cj;
      double cjratio = IDA_mem->ida_cjratio;

      IDA_mem = (IDAMem) IDA_mem->ida_user_data;

      IDAADJ_mem = IDA_mem->ida_adj_mem;
      //IDAB_mem = IDAADJ_mem->ia_bckpbCrt;

      // Get FORWARD solution from interpolation.
      if (IDAADJ_mem->ia_noInterp==FALSE) {
        flag = IDAADJ_mem->ia_getY(IDA_mem, t, IDAADJ_mem->ia_yyTmp, IDAADJ_mem->ia_ypTmp,
                                   NULL, NULL);
        if (flag != IDA_SUCCESS) casadi_error("Could not interpolate forward states");
      }

      // Accuracy
      double delta = 0.0;

      // Call the preconditioner solve function (which solves the linear system)
      if (psolveB(t, IDAADJ_mem->ia_yyTmp, IDAADJ_mem->ia_ypTmp, xzB, xzdotB,
        rrB, b, b, cj, delta, static_cast<void*>(m), 0)) return 1;

      // Scale the correction to account for change in cj
      if (s.cj_scaling_) {
        if (cjratio != 1.0) N_VScale(2.0/(1.0 + cjratio), b, b);
      }
      return 0;
    } catch(int flag) { // recoverable error
      return flag;
    } catch(exception& e) { // non-recoverable error
      userOut<true, PL_WARN>() << "lsolveB failed: " << e.what() << endl;
      return -1;
    }
  }