void SymbolBehavior::fromJson(const QJsonObject &json) { ItemBehavior::fromJson(json); int type = json.value(DataKey::SymbolType).toInt(); setData(type, LP::SymbolType); int instrument = json.value(DataKey::Instrument).toInt(); setData(instrument, LP::SymbolInstrument); QString name = json.value(DataKey::SymbolName).toString(); setData(name, LP::SymbolName); if (hasOption(HasLength)) { int length = json.value(DataKey::Lenght).toInt(); Length::Value lengthValue = static_cast<Length::Value>(length); setData(QVariant::fromValue<Length::Value>(lengthValue), LP::SymbolLength); } if (hasOption(HasPitch)) { QJsonObject pitchObject = json.value(DataKey::Pitch).toObject(); Pitch pitch; pitch.fromJson(pitchObject); setData(QVariant::fromValue<Pitch>(pitch), LP::SymbolPitch); } int spanType = json.value(DataKey::SymbolSpanType).toInt(); if (spanType != 0) { SpanType type = static_cast<SpanType>(spanType); setData(QVariant::fromValue<SpanType>(type), LP::SymbolSpanType); } }
shared_ptr<Scene> SceneParser::readScene() { loadConfig(fname); /* * the scene being constructed */ shared_ptr<Scene> s = make_shared<Scene>(); /* * directory containing assets */ string basepath = options["directory"]; // load data from image file if ( hasOption("photo_color") ) { string colorpath = basepath + options["photo_color"]; Mat pcolor = imread(colorpath, CV_LOAD_IMAGE_COLOR); s->setPhoto(pcolor); } if ( hasOption("photo_depth") ) { string depthpath = basepath + options["photo_depth"]; Mat pdepth = imread(depthpath, CV_LOAD_IMAGE_COLOR); s->setDepthPhoto(pdepth); } if ( hasOption("lightmap") ) { string lmpath = basepath + options["lightmap"]; Mat lmap = imread(lmpath, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); s->setLightMap(lmap); } if ( hasOption("local_model") ) { s->addGeometry(basepath + options["local_model"], true); } if ( hasOption("virtual_model") ) { s->addGeometry(basepath + options["virtual_model"], false); } if ( hasOption("camera") ) { //s->setCamAngle(glm::quat(-0.0754814, 6.97229e-05, 0.989809, -0.121214), glm::vec3(-0.24233, 0.804301, -0.098939), 10.1601, 15.0); } if ( hasOption("camera_angle") ) { vector<string> a = split(options["camera_angle"], ','); s->setCamAngle( glm::quat(stof(a[0]), stof(a[1]), stof(a[2]), stof(a[3])) ); } if ( hasOption("camera_pos") ) { vector<string> a = split(options["camera_pos"], ','); s->setCamPos( glm::vec3(stof(a[0]), stof(a[1]), stof(a[2])) ); } if ( hasOption("camera_zoom") ) { s->setCamZoom( stof(options["camera_zoom"]) ); } if ( hasOption("camera_vfov") ) { s->setCamFov( stof(options["camera_vfov"]) ); } return s; }
QJsonObject SymbolBehavior::toJson() const { QJsonObject json(ItemBehavior::toJson()); int symbolType = data(LP::SymbolType).toInt(); if (symbolType != LP::NoSymbolType) { json.insert(DataKey::SymbolType, symbolType); } json.insert(DataKey::Instrument, data(LP::SymbolInstrument).toInt()); json.insert(DataKey::SymbolName, data(LP::SymbolName).toString()); if (hasOption(HasLength)) { Length::Value length = data(LP::SymbolLength).value<Length::Value>(); json.insert(DataKey::Lenght, static_cast<int>(length)); } if (hasOption(HasPitch)) { Pitch pitch = data(LP::SymbolPitch).value<Pitch>(); json.insert(DataKey::Pitch, pitch.toJson()); } SpanType spanType = data(LP::SymbolSpanType).value<SpanType>(); if (spanType != SpanType::None) { json.insert(DataKey::SymbolSpanType, static_cast<int>(spanType)); } return json; }
std::string Tariff::getOption( std::string name, std::string country ) { if ( hasOption( name, country ) == true ) return tariff.countries[ country ].options[ name ]; if ( hasOption( name ) == true ) return tariff.options[ name ]; return ""; }
int main (const int argc, const char* argv[]) { if (hasOption(argc, argv, "-h") || hasOption(argc, argv, "--help")) { showHelp(); // Terminates the program after the help is shown. return 0; } if (hasOption(argc, argv, "--verbose")) { ::demo::isVerbose = true; } // Initialises WiringPi and uses the BCM pin layout. // For an overview on the pin layout, use the `gpio readall` command on a Raspberry Pi. ::wiringPiSetupGpio(); demo::ExtensionSensors extensionSensors(demo::Gpio::allocateSpi(), {0, 1, 2, 3, 4, 5}, 0.168, 0.268); extensionSensors.setNumberOfSamplesPerMeasurment(3); arma::Mat<double> extensionSensorsCorrection; if (extensionSensorsCorrection.load("extensionSensors.correction")) { std::cout << "Using the extension sensor correction." << std::endl; extensionSensors.setMeasurementCorrections(extensionSensorsCorrection); } else { std::cout << "Could not find extension sensor correction file. Displaying uncorrected measurements." << std::endl; } std::vector<demo::Pin> directionPins; directionPins.push_back(demo::Gpio::allocatePin(22)); directionPins.push_back(demo::Gpio::allocatePin(5)); directionPins.push_back(demo::Gpio::allocatePin(6)); directionPins.push_back(demo::Gpio::allocatePin(13)); directionPins.push_back(demo::Gpio::allocatePin(19)); directionPins.push_back(demo::Gpio::allocatePin(26)); demo::ServoControllers servoControllers(std::move(directionPins), demo::Gpio::allocateI2c(), {0, 1, 2, 3, 4, 5}, 1.0); demo::LinearActuators linearActuators(std::move(servoControllers), std::move(extensionSensors), 0.178, 0.248); linearActuators.setAcceptableExtensionDeviation(0.005); demo::AttitudeSensors attitudeSensors(demo::Gpio::allocateUart(), -arma::datum::pi, arma::datum::pi); arma::Mat<double>::fixed<3, 6> baseJointsPosition; baseJointsPosition.load("baseJointsPosition.config"); arma::Mat<double>::fixed<3, 6> endEffectorJointsRelativePosition; endEffectorJointsRelativePosition.load("endEffectorJointsRelativePosition.config"); demo::StewartPlatform stewartPlatform(std::move(linearActuators), std::move(attitudeSensors), baseJointsPosition, endEffectorJointsRelativePosition, {-0.02, -0.02, 0.21, -0.2, -0.2, -0.6}, {0.02, 0.02, 0.27, 0.2, 0.2, 0.6}); if (hasOption(argc, argv, "sensor")) { runSensor(stewartPlatform); } if (argc > 6 && isNumber(argv[1]) && isNumber(argv[2]) && isNumber(argv[3]) && isNumber(argv[4]) && isNumber(argv[5]) && isNumber(argv[6])) { runEndEffectorPose(stewartPlatform, {std::stod(argv[1]), std::stod(argv[2]), std::stod(argv[3]), std::stod(argv[4]), std::stod(argv[5]), std::stod(argv[6])}); } else { runDefault(stewartPlatform); } return 0; }
bool AdBlockRule::urlMatch(const QUrl &url) const { if (!hasOption(DocumentOption) && !hasOption(ElementHideOption)) { return false; } const QString encodedUrl = url.toEncoded(); const QString domain = url.host(); return networkMatch(QNetworkRequest(url), domain, encodedUrl); }
bool AdBlockRule::networkMatch(const QWebEngineUrlRequestInfo &request, const QString &domain, const QString &encodedUrl) const { if (m_type == CssRule || !m_isEnabled || m_isInternalDisabled) { return false; } bool matched = stringMatch(domain, encodedUrl); if (matched) { // Check domain restrictions if (hasOption(DomainRestrictedOption) && !matchDomain(request.firstPartyUrl().host())) { return false; } // Check third-party restriction if (hasOption(ThirdPartyOption) && !matchThirdParty(request)) { return false; } // Check object restrictions if (hasOption(ObjectOption) && !matchObject(request)) { return false; } // Check subdocument restriction if (hasOption(SubdocumentOption) && !matchSubdocument(request)) { return false; } // Check xmlhttprequest restriction if (hasOption(XMLHttpRequestOption) && !matchXmlHttpRequest(request)) { return false; } // Check image restriction if (hasOption(ImageOption) && !matchImage(request)) { return false; } // Check script restriction if (hasOption(ScriptOption) && !matchScript(request)) { return false; } // Check stylesheet restriction if (hasOption(StyleSheetOption) && !matchStyleSheet(request)) { return false; } // Check object-subrequest restriction if (hasOption(ObjectSubrequestOption) && !matchObjectSubrequest(request)) { return false; } } return matched; }
/** --displayWithOptions Generic display options diplaying the results considering the options given in parameter by console command inputs: -lines(Maillon*) : a linked list of the resulting FileLines from the inital command - args(Arguments*) : a linked list of the arguments given in parameter by console command **/ void displayWithOptions(Maillon* lines, Arguments* args) { short has_n = hasOption('n', args->options); int file_count = listSize(args->files); displayFileLine(lines, file_count, has_n); }
TEST(OptionsTest, test_static_options) { Options ops; FauxReader reader; reader.setOptions(ops); CropFilter crop; crop.setOptions(ops); crop.setInput(reader); auto opts = crop.getDefaultOptions(); EXPECT_EQ(opts.getOptions().size(), 4u); EXPECT_TRUE(opts.hasOption("bounds")); EXPECT_TRUE(opts.hasOption("inside")); EXPECT_TRUE(opts.hasOption("polygon")); EXPECT_FALSE(opts.hasOption("metes")); }
int main (const int argc, const char* argv[]) { if (hasOption(argc, argv, "-h") || hasOption(argc, argv, "--help")) { showHelp(); // Terminates the program after the help is shown. return 0; } if (hasOption(argc, argv, "--verbose")) { ::demo::isVerbose = true; } demo::Mouse3dSensors mouse3dSensors(-1, 1); runDefault(mouse3dSensors); return 0; }
void NLPSolverInternal::reportConstraints(std::ostream &stream) { stream << "Reporting NLP constraints" << endl; CasADi::reportConstraints(stream,output(NLP_X_OPT),input(NLP_LBX),input(NLP_UBX), "decision bounds"); double tol = 1e-8; if (hasOption("constr_viol_tol")) tol = getOption("constr_viol_tol"); CasADi::reportConstraints(stream,output(NLP_G),input(NLP_LBG),input(NLP_UBG), "constraints",getOption("constr_viol_tol")); }
const LLCommandLineParser::token_vector_t& LLCommandLineParser::getOption(const std::string& name) const { if(hasOption(name)) { return gVariableMap[name].as<token_vector_t>(); } return gEmptyValue; }
void CsvChunkLoader::openHook() { _csvParser .setFilePtr(fp()) .setLogger(logger); if (hasOption('p')) { _csvParser.setDelim('|'); } else if (hasOption('t')) { _csvParser.setDelim('\t'); } if (hasOption('d')) { _csvParser.setQuote('\"'); } else if (hasOption('s')) { _csvParser.setQuote('\''); } }
boost::logic::tribool Tariff::hasOption( std::string name, std::string country ) { if ( tariff.countries.find( country ) != tariff.countries.end() ) if ( tariff.countries[ country ].options.find( name ) != tariff.countries[ country ].options.end() ) return true; boost::logic::tribool r = hasOption( name ); if ( r == true ) return boost::logic::indeterminate_keyword_t(); return r; }
bool OptionContainer::addOption(Option o) { if (o.getType()==OptionContainer::Option::EInvalid) { return false; } if (hasOption(o)){ return false; } m_Options.push_back(o); return true; }
double Tariff::costs( std::string cname, std::string opcode ) { if ( hasOption( "price", cname, opcode ) ) { try { double price = boost::lexical_cast< double >( getOption( "price", cname, opcode ) ); return currencyConvert( getOption< TariffCurrency >( cname, opcode ), TariffCurrency(), price ); } catch ( ... ) { return INVALID_VALUE; } } else if ( !hasOption( "price", cname, opcode ) ) { if ( hasOption< TariffOptionUnknownPolicy >( cname, opcode ) == false ) return INVALID_VALUE; else { return costs( cname ); } } return costs( cname ); }
bool AdBlockRule::networkMatch(const QNetworkRequest &request, const QString &domain, const QString &encodedUrl) const { if (m_type == CssRule || !m_isEnabled || m_isInternalDisabled) { return false; } bool matched = false; if (m_type == StringContainsMatchRule) { matched = encodedUrl.contains(m_matchString, m_caseSensitivity); } else if (m_type == DomainMatchRule) { matched = isMatchingDomain(domain, m_matchString); } else if (m_type == StringEndsMatchRule) { matched = encodedUrl.endsWith(m_matchString, m_caseSensitivity); } else if (m_type == RegExpMatchRule) { if (!isMatchingRegExpStrings(encodedUrl)) { return false; } matched = (m_regExp->regExp.indexIn(encodedUrl) != -1); } if (matched) { // Check domain restrictions if (hasOption(DomainRestrictedOption) && !matchDomain(domain)) { return false; } // Check third-party restriction if (hasOption(ThirdPartyOption) && !matchThirdParty(request)) { return false; } // Check object restrictions if (hasOption(ObjectOption) && !matchObject(request)) { return false; } // Check subdocument restriction if (hasOption(SubdocumentOption) && !matchSubdocument(request)) { return false; } // Check xmlhttprequest restriction if (hasOption(XMLHttpRequestOption) && !matchXmlHttpRequest(request)) { return false; } // Check image restriction if (hasOption(ImageOption) && !matchImage(encodedUrl)) { return false; } } return matched; }
int ServiceDaemon::pre_initialize() { // // Parse command line options // parseOptions(); if (hasOption("daemonize")) { if (!hasOption("pid-file")) { std::cerr << "You need to specify a PID file when running as daemon!" << std::endl; displayUsage(std::cerr); return -1; } getOption("pid-file", _pidFile); OSS::app_set_pid_file(_pidFile); daemonize(); } return 0; }
bool AdBlockRule::matchDomain(const QString &domain) const { if (!m_isEnabled) { return false; } if (!hasOption(DomainRestrictedOption)) { return true; } if (m_blockedDomains.isEmpty()) { foreach (const QString &d, m_allowedDomains) { if (isMatchingDomain(domain, d)) { return true; } } }
int sdisk_unix_t::convert_flags(int sflags) { int flags = 0; /* 1 of n */ switch (modeBits(sflags)) { case OPEN_RDWR: flags |= O_RDWR; break; case OPEN_WRONLY: flags |= O_WRONLY; break; case OPEN_RDONLY: flags |= O_RDONLY; break; } /* m of n */ /* could make a data driven flag conversion, :-) */ if (hasOption(sflags, OPEN_CREATE)) flags |= O_CREAT; if (hasOption(sflags, OPEN_TRUNC)) flags |= O_TRUNC; if (hasOption(sflags, OPEN_EXCL)) flags |= O_EXCL; #ifdef O_SYNC if (hasOption(sflags, OPEN_SYNC)) flags |= O_SYNC; #endif if (hasOption(sflags, OPEN_APPEND)) flags |= O_APPEND; #ifdef O_DIRECT /* * From the open man page: * O_DIRECT Try to minimize cache effects of the I/O to and from this file. In general this will degrade performance, but it is useful in special situations, such as when applications do their own caching. File I/O is done directly to/from user space buffers. The I/O is synchronous, i.e., at the completion of a read(2) or write(2), data is guaranteed to have been transferred. Under Linux 2.4 transfer sizes, and the alignment of user buffer and file offset must all be multiples of the logical block size of the file system. Under Linux 2.6 alignment must fit the block size of the device. */ if (hasOption(sflags, OPEN_RAW)) flags |= O_DIRECT; #endif return flags; }
//------------------------------------------------------------------------------ bool SzCmd::doExecute() { TreeArgHandler* handler = static_cast<TreeArgHandler*>(mArgHandler); const std::string& branch = handler->getMatchedBranch(); bool recursive = !hasOption('R'); const std::string& fileName = handler->getMatchedNodeValue("id"); boost::filesystem::ofstream ofs(fileName, std::fstream::trunc); AbsDir* curDir = sgConsole.getCwd(); if (branch == "0") { // sz id curDir->serialize(ofs, recursive); } else if (branch == "1") { // sz id path AbsDir* dir = AbsDirUtil::findPath(handler->getMatchedNodeValue("path"), curDir); dir->serialize(ofs, recursive); } else { PAC_EXCEPT(Exception::ERR_INVALID_STATE, "unknown branch"); } return true; }
std::ostream& ConversionJob::printTo(std::ostream& out) const { out << "~~~~~~CONVERSION SETUP~~~~~~\n"; out << "input files: \n" << files << std::endl; out << "flags: \n" << "PrintDiag " << hasOption(ConversionSetup::PrintDiag) << "\n" << "WinCrossCompile " << hasOption(ConversionSetup::WinCrossCompile) << "\n" << "TAG_MPI " << hasOption(ConversionSetup::TAG_MPI) << "\n" << "ProgressBar " << hasOption(ConversionSetup::ProgressBar) << "\n" << "NoWarnings " << hasOption(ConversionSetup::NoWarnings) << "\n" << "NoDefaultExtensions " << hasOption(ConversionSetup::NoDefaultExtensions) << "\n" << std::endl; out << "interceptions: \n" << getInterceptedNameSpacePatterns() << std::endl; out << "crosscompilation dir: \n" << getCrossCompilationSystemHeadersDir() << std::endl; out << "include dirs: \n" << getIncludeDirectories() << std::endl; out << "definitions: \n" << getDefinitions() << std::endl; out << "libraries: \n" << libs << std::endl; out << "standard: \n" << getStandard() << std::endl; out << "number of registered extensions: \n" << getExtensions().size() << std::endl; out << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; return out; }
double Tariff::costs( std::string cname ) { if ( hasOption( "price", cname ) ) { try { double price = boost::lexical_cast< double >( getOption( "price", cname ) ); return currencyConvert( getOption< TariffCurrency >( cname ), TariffCurrency(), price ); } catch ( ... ) { return INVALID_VALUE; } } else if ( !hasOption( "price", cname ) ) { if ( hasOption< TariffOptionUnknownPolicy >( cname ) == false ) return INVALID_VALUE; else { double price; if ( tariff.countries.find( cname ) != tariff.countries.end() ) { TariffOptionUnknownPolicy policy = getOption< TariffOptionUnknownPolicy >( cname ); if ( policy.getValue() == "FREE" ) price = 0.0; double maxval = INVALID_VALUE; if ( policy.getValue() == "MAXIMUM" ) { for ( std::map< std::string, TariffOperatorInfo >::iterator it = tariff.countries[ cname ].operators.begin(); it != tariff.countries[ cname ].operators.end(); it++ ) { std::string mnc = it->first; if ( hasOption( "price", cname, mnc ) ) try { double price = boost::lexical_cast< double >( getOption( "price", cname, mnc ) ); price = currencyConvert( getOption< TariffCurrency >( cname, mnc ), TariffCurrency(), price ); maxval = std::max( maxval, price ); } catch ( ... ) {} } price = maxval; } double sum = 0; double total = 0; if ( policy.getValue() == "AVERAGE" ) { for ( std::map< std::string, TariffOperatorInfo >::iterator it = tariff.countries[ cname ].operators.begin(); it != tariff.countries[ cname ].operators.end(); it++ ) { std::string mnc = it->first; if ( hasOption( "price", cname, mnc ) ) { try { double price = boost::lexical_cast< double >( getOption( "price", cname, mnc ) ); price = currencyConvert( getOption< TariffCurrency >( cname, mnc ), TariffCurrency(), price ); sum += price; } catch ( ... ) { continue; } total++; } } price = total == 0? INVALID_VALUE: sum/total; } return price; } else return INVALID_VALUE; } } try { double price = boost::lexical_cast< double >( getOption( "price" ) ); return currencyConvert( getOption< TariffCurrency >( cname ), TariffCurrency(), price ); } catch ( ... ) { return INVALID_VALUE; } }
void Sqpmethod::evaluate() { if (inputs_check_) checkInputs(); checkInitialBounds(); if (gather_stats_) { Dict iterations; iterations["inf_pr"] = std::vector<double>(); iterations["inf_du"] = std::vector<double>(); iterations["ls_trials"] = std::vector<double>(); iterations["d_norm"] = std::vector<double>(); iterations["obj"] = std::vector<double>(); stats_["iterations"] = iterations; } // Get problem data const vector<double>& x_init = input(NLP_SOLVER_X0).data(); const vector<double>& lbx = input(NLP_SOLVER_LBX).data(); const vector<double>& ubx = input(NLP_SOLVER_UBX).data(); const vector<double>& lbg = input(NLP_SOLVER_LBG).data(); const vector<double>& ubg = input(NLP_SOLVER_UBG).data(); // Set linearization point to initial guess copy(x_init.begin(), x_init.end(), x_.begin()); // Initialize Lagrange multipliers of the NLP copy(input(NLP_SOLVER_LAM_G0).begin(), input(NLP_SOLVER_LAM_G0).end(), mu_.begin()); copy(input(NLP_SOLVER_LAM_X0).begin(), input(NLP_SOLVER_LAM_X0).end(), mu_x_.begin()); t_eval_f_ = t_eval_grad_f_ = t_eval_g_ = t_eval_jac_g_ = t_eval_h_ = t_callback_fun_ = t_callback_prepare_ = t_mainloop_ = 0; n_eval_f_ = n_eval_grad_f_ = n_eval_g_ = n_eval_jac_g_ = n_eval_h_ = 0; double time1 = clock(); // Initial constraint Jacobian eval_jac_g(x_, gk_, Jk_); // Initial objective gradient eval_grad_f(x_, fk_, gf_); // Initialize or reset the Hessian or Hessian approximation reg_ = 0; if (exact_hessian_) { eval_h(x_, mu_, 1.0, Bk_); } else { reset_h(); } // Evaluate the initial gradient of the Lagrangian copy(gf_.begin(), gf_.end(), gLag_.begin()); if (ng_>0) casadi_mv_t(Jk_.ptr(), Jk_.sparsity(), getPtr(mu_), getPtr(gLag_)); // gLag += mu_x_; transform(gLag_.begin(), gLag_.end(), mu_x_.begin(), gLag_.begin(), plus<double>()); // Number of SQP iterations int iter = 0; // Number of line-search iterations int ls_iter = 0; // Last linesearch successfull bool ls_success = true; // Reset merit_mem_.clear(); sigma_ = 0.; // NOTE: Move this into the main optimization loop // Default stepsize double t = 0; // MAIN OPTIMIZATION LOOP while (true) { // Primal infeasability double pr_inf = primalInfeasibility(x_, lbx, ubx, gk_, lbg, ubg); // inf-norm of lagrange gradient double gLag_norminf = norm_inf(gLag_); // inf-norm of step double dx_norminf = norm_inf(dx_); // Print header occasionally if (iter % 10 == 0) printIteration(userOut()); // Printing information about the actual iterate printIteration(userOut(), iter, fk_, pr_inf, gLag_norminf, dx_norminf, reg_, ls_iter, ls_success); if (gather_stats_) { Dict iterations = stats_["iterations"]; std::vector<double> tmp=iterations["inf_pr"]; tmp.push_back(pr_inf); iterations["inf_pr"] = tmp; tmp=iterations["inf_du"]; tmp.push_back(gLag_norminf); iterations["inf_du"] = tmp; tmp=iterations["d_norm"]; tmp.push_back(dx_norminf); iterations["d_norm"] = tmp; std::vector<int> tmp2=iterations["ls_trials"]; tmp2.push_back(ls_iter); iterations["ls_trials"] = tmp2; tmp=iterations["obj"]; tmp.push_back(fk_); iterations["obj"] = tmp; stats_["iterations"] = iterations; } // Call callback function if present if (!callback_.isNull()) { double time1 = clock(); if (!output(NLP_SOLVER_F).isempty()) output(NLP_SOLVER_F).set(fk_); if (!output(NLP_SOLVER_X).isempty()) output(NLP_SOLVER_X).setNZ(x_); if (!output(NLP_SOLVER_LAM_G).isempty()) output(NLP_SOLVER_LAM_G).setNZ(mu_); if (!output(NLP_SOLVER_LAM_X).isempty()) output(NLP_SOLVER_LAM_X).setNZ(mu_x_); if (!output(NLP_SOLVER_G).isempty()) output(NLP_SOLVER_G).setNZ(gk_); Dict iteration; iteration["iter"] = iter; iteration["inf_pr"] = pr_inf; iteration["inf_du"] = gLag_norminf; iteration["d_norm"] = dx_norminf; iteration["ls_trials"] = ls_iter; iteration["obj"] = fk_; stats_["iteration"] = iteration; double time2 = clock(); t_callback_prepare_ += (time2-time1)/CLOCKS_PER_SEC; time1 = clock(); int ret = callback_(ref_, user_data_); time2 = clock(); t_callback_fun_ += (time2-time1)/CLOCKS_PER_SEC; if (ret) { userOut() << endl; userOut() << "casadi::SQPMethod: aborted by callback..." << endl; stats_["return_status"] = "User_Requested_Stop"; break; } } // Checking convergence criteria if (pr_inf < tol_pr_ && gLag_norminf < tol_du_) { userOut() << endl; userOut() << "casadi::SQPMethod: Convergence achieved after " << iter << " iterations." << endl; stats_["return_status"] = "Solve_Succeeded"; break; } if (iter >= max_iter_) { userOut() << endl; userOut() << "casadi::SQPMethod: Maximum number of iterations reached." << endl; stats_["return_status"] = "Maximum_Iterations_Exceeded"; break; } if (iter > 0 && dx_norminf <= min_step_size_) { userOut() << endl; userOut() << "casadi::SQPMethod: Search direction becomes too small without " "convergence criteria being met." << endl; stats_["return_status"] = "Search_Direction_Becomes_Too_Small"; break; } // Start a new iteration iter++; log("Formulating QP"); // Formulate the QP transform(lbx.begin(), lbx.end(), x_.begin(), qp_LBX_.begin(), minus<double>()); transform(ubx.begin(), ubx.end(), x_.begin(), qp_UBX_.begin(), minus<double>()); transform(lbg.begin(), lbg.end(), gk_.begin(), qp_LBA_.begin(), minus<double>()); transform(ubg.begin(), ubg.end(), gk_.begin(), qp_UBA_.begin(), minus<double>()); // Solve the QP solve_QP(Bk_, gf_, qp_LBX_, qp_UBX_, Jk_, qp_LBA_, qp_UBA_, dx_, qp_DUAL_X_, qp_DUAL_A_); log("QP solved"); // Detecting indefiniteness double gain = casadi_quad_form(Bk_.ptr(), Bk_.sparsity(), getPtr(dx_)); if (gain < 0) { casadi_warning("Indefinite Hessian detected..."); } // Calculate penalty parameter of merit function sigma_ = std::max(sigma_, 1.01*norm_inf(qp_DUAL_X_)); sigma_ = std::max(sigma_, 1.01*norm_inf(qp_DUAL_A_)); // Calculate L1-merit function in the actual iterate double l1_infeas = primalInfeasibility(x_, lbx, ubx, gk_, lbg, ubg); // Right-hand side of Armijo condition double F_sens = inner_prod(dx_, gf_); double L1dir = F_sens - sigma_ * l1_infeas; double L1merit = fk_ + sigma_ * l1_infeas; // Storing the actual merit function value in a list merit_mem_.push_back(L1merit); if (merit_mem_.size() > merit_memsize_) { merit_mem_.pop_front(); } // Stepsize t = 1.0; double fk_cand; // Merit function value in candidate double L1merit_cand = 0; // Reset line-search counter, success marker ls_iter = 0; ls_success = true; // Line-search log("Starting line-search"); if (max_iter_ls_>0) { // max_iter_ls_== 0 disables line-search // Line-search loop while (true) { for (int i=0; i<nx_; ++i) x_cand_[i] = x_[i] + t * dx_[i]; try { // Evaluating objective and constraints eval_f(x_cand_, fk_cand); eval_g(x_cand_, gk_cand_); } catch(const CasadiException& ex) { // Silent ignore; line-search failed ls_iter++; // Backtracking t = beta_ * t; continue; } ls_iter++; // Calculating merit-function in candidate l1_infeas = primalInfeasibility(x_cand_, lbx, ubx, gk_cand_, lbg, ubg); L1merit_cand = fk_cand + sigma_ * l1_infeas; // Calculating maximal merit function value so far double meritmax = *max_element(merit_mem_.begin(), merit_mem_.end()); if (L1merit_cand <= meritmax + t * c1_ * L1dir) { // Accepting candidate log("Line-search completed, candidate accepted"); break; } // Line-search not successful, but we accept it. if (ls_iter == max_iter_ls_) { ls_success = false; log("Line-search completed, maximum number of iterations"); break; } // Backtracking t = beta_ * t; } // Candidate accepted, update dual variables for (int i=0; i<ng_; ++i) mu_[i] = t * qp_DUAL_A_[i] + (1 - t) * mu_[i]; for (int i=0; i<nx_; ++i) mu_x_[i] = t * qp_DUAL_X_[i] + (1 - t) * mu_x_[i]; // Candidate accepted, update the primal variable copy(x_.begin(), x_.end(), x_old_.begin()); copy(x_cand_.begin(), x_cand_.end(), x_.begin()); } else { // Full step copy(qp_DUAL_A_.begin(), qp_DUAL_A_.end(), mu_.begin()); copy(qp_DUAL_X_.begin(), qp_DUAL_X_.end(), mu_x_.begin()); copy(x_.begin(), x_.end(), x_old_.begin()); // x+=dx transform(x_.begin(), x_.end(), dx_.begin(), x_.begin(), plus<double>()); } if (!exact_hessian_) { // Evaluate the gradient of the Lagrangian with the old x but new mu (for BFGS) copy(gf_.begin(), gf_.end(), gLag_old_.begin()); if (ng_>0) casadi_mv_t(Jk_.ptr(), Jk_.sparsity(), getPtr(mu_), getPtr(gLag_old_)); // gLag_old += mu_x_; transform(gLag_old_.begin(), gLag_old_.end(), mu_x_.begin(), gLag_old_.begin(), plus<double>()); } // Evaluate the constraint Jacobian log("Evaluating jac_g"); eval_jac_g(x_, gk_, Jk_); // Evaluate the gradient of the objective function log("Evaluating grad_f"); eval_grad_f(x_, fk_, gf_); // Evaluate the gradient of the Lagrangian with the new x and new mu copy(gf_.begin(), gf_.end(), gLag_.begin()); if (ng_>0) casadi_mv_t(Jk_.ptr(), Jk_.sparsity(), getPtr(mu_), getPtr(gLag_)); // gLag += mu_x_; transform(gLag_.begin(), gLag_.end(), mu_x_.begin(), gLag_.begin(), plus<double>()); // Updating Lagrange Hessian if (!exact_hessian_) { log("Updating Hessian (BFGS)"); // BFGS with careful updates and restarts if (iter % lbfgs_memory_ == 0) { // Reset Hessian approximation by dropping all off-diagonal entries const int* colind = Bk_.colind(); // Access sparsity (column offset) int ncol = Bk_.size2(); const int* row = Bk_.row(); // Access sparsity (row) vector<double>& data = Bk_.data(); // Access nonzero elements for (int cc=0; cc<ncol; ++cc) { // Loop over the columns of the Hessian for (int el=colind[cc]; el<colind[cc+1]; ++el) { // Loop over the nonzero elements of the column if (cc!=row[el]) data[el] = 0; // Remove if off-diagonal entries } } } // Pass to BFGS update function bfgs_.setInput(Bk_, BFGS_BK); bfgs_.setInputNZ(x_, BFGS_X); bfgs_.setInputNZ(x_old_, BFGS_X_OLD); bfgs_.setInputNZ(gLag_, BFGS_GLAG); bfgs_.setInputNZ(gLag_old_, BFGS_GLAG_OLD); // Update the Hessian approximation bfgs_.evaluate(); // Get the updated Hessian bfgs_.getOutput(Bk_); if (monitored("bfgs")) { userOut() << "x = " << x_ << endl; userOut() << "BFGS = " << endl; Bk_.printSparse(); } } else { // Exact Hessian log("Evaluating hessian"); eval_h(x_, mu_, 1.0, Bk_); } } double time2 = clock(); t_mainloop_ = (time2-time1)/CLOCKS_PER_SEC; // Save results to outputs output(NLP_SOLVER_F).set(fk_); output(NLP_SOLVER_X).setNZ(x_); output(NLP_SOLVER_LAM_G).setNZ(mu_); output(NLP_SOLVER_LAM_X).setNZ(mu_x_); output(NLP_SOLVER_G).setNZ(gk_); if (hasOption("print_time") && static_cast<bool>(getOption("print_time"))) { // Write timings userOut() << "time spent in eval_f: " << t_eval_f_ << " s."; if (n_eval_f_>0) userOut() << " (" << n_eval_f_ << " calls, " << (t_eval_f_/n_eval_f_)*1000 << " ms. average)"; userOut() << endl; userOut() << "time spent in eval_grad_f: " << t_eval_grad_f_ << " s."; if (n_eval_grad_f_>0) userOut() << " (" << n_eval_grad_f_ << " calls, " << (t_eval_grad_f_/n_eval_grad_f_)*1000 << " ms. average)"; userOut() << endl; userOut() << "time spent in eval_g: " << t_eval_g_ << " s."; if (n_eval_g_>0) userOut() << " (" << n_eval_g_ << " calls, " << (t_eval_g_/n_eval_g_)*1000 << " ms. average)"; userOut() << endl; userOut() << "time spent in eval_jac_g: " << t_eval_jac_g_ << " s."; if (n_eval_jac_g_>0) userOut() << " (" << n_eval_jac_g_ << " calls, " << (t_eval_jac_g_/n_eval_jac_g_)*1000 << " ms. average)"; userOut() << endl; userOut() << "time spent in eval_h: " << t_eval_h_ << " s."; if (n_eval_h_>1) userOut() << " (" << n_eval_h_ << " calls, " << (t_eval_h_/n_eval_h_)*1000 << " ms. average)"; userOut() << endl; userOut() << "time spent in main loop: " << t_mainloop_ << " s." << endl; userOut() << "time spent in callback function: " << t_callback_fun_ << " s." << endl; userOut() << "time spent in callback preparation: " << t_callback_prepare_ << " s." << endl; } // Save statistics stats_["iter_count"] = iter; stats_["t_eval_f"] = t_eval_f_; stats_["t_eval_grad_f"] = t_eval_grad_f_; stats_["t_eval_g"] = t_eval_g_; stats_["t_eval_jac_g"] = t_eval_jac_g_; stats_["t_eval_h"] = t_eval_h_; stats_["t_mainloop"] = t_mainloop_; stats_["t_callback_fun"] = t_callback_fun_; stats_["t_callback_prepare"] = t_callback_prepare_; stats_["n_eval_f"] = n_eval_f_; stats_["n_eval_grad_f"] = n_eval_grad_f_; stats_["n_eval_g"] = n_eval_g_; stats_["n_eval_jac_g"] = n_eval_jac_g_; stats_["n_eval_h"] = n_eval_h_; }
void Tariff::removeOption( std::string name, std::string country, std::string oper ) { if ( hasOption( name, country, oper ) == true ) tariff.countries[ country ].operators[ oper ].options.erase( name ); }
T AbstractProperty::option(const std::string & key, const T & defaultValue) const { return hasOption(key) ? option(key).value<T>(defaultValue) : defaultValue; }
bool AdBlockRule::isDomainRestricted() const { return hasOption(DomainRestrictedOption); }
bool AdBlockRule::isElemhide() const { return hasOption(ElementHideOption); }
bool AdBlockRule::isDocument() const { return hasOption(DocumentOption); }
bool OptionsFunctionalityNode::hasSetOption(const string &str) const{ if(!hasOption(str)) casadi_error("OptionsFunctionalityNode::hasSetOption: no such option '" << str << "'"); Dictionary::const_iterator it = dictionary_.find(str); return it != dictionary_.end(); }