/*!\reimp */ void QLabel::paintEvent(QPaintEvent *) { Q_D(QLabel); QStyle *style = QWidget::style(); QPainter painter(this); drawFrame(&painter); QRect cr = contentsRect(); cr.adjust(d->margin, d->margin, -d->margin, -d->margin); int align = QStyle::visualAlignment(layoutDirection(), QFlag(d->align)); #ifndef QT_NO_MOVIE if (d->movie) { if (d->scaledcontents) style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size())); else style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap()); } else #endif if (d->isTextLabel) { QRectF lr = d->layoutRect(); if (d->control) { #ifndef QT_NO_SHORTCUT const bool underline = (bool)style->styleHint(QStyle::SH_UnderlineShortcut, 0, this, 0); if (d->shortcutId != 0 && underline != d->shortcutCursor.charFormat().fontUnderline()) { QTextCharFormat fmt; fmt.setFontUnderline(underline); d->shortcutCursor.mergeCharFormat(fmt); } #endif d->ensureTextLayouted(); QAbstractTextDocumentLayout::PaintContext context; QStyleOption opt(0); opt.init(this); if (!isEnabled() && style->styleHint(QStyle::SH_EtchDisabledText, &opt, this)) { context.palette = palette(); context.palette.setColor(QPalette::Text, context.palette.light().color()); painter.save(); painter.translate(lr.x() + 1, lr.y() + 1); painter.setClipRect(lr.translated(-lr.x() - 1, -lr.y() - 1)); QAbstractTextDocumentLayout *layout = d->control->document()->documentLayout(); layout->draw(&painter, context); painter.restore(); } // Adjust the palette context.palette = palette(); if (foregroundRole() != QPalette::Text && isEnabled()) context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole())); painter.save(); painter.translate(lr.topLeft()); painter.setClipRect(lr.translated(-lr.x(), -lr.y())); d->control->setPalette(context.palette); d->control->drawContents(&painter, QRectF(), this); painter.restore(); } else { int flags = align; if (d->hasShortcut) { flags |= Qt::TextShowMnemonic; QStyleOption opt; opt.initFrom(this); if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this)) flags |= Qt::TextHideMnemonic; } style->drawItemText(&painter, lr.toRect(), flags, palette(), isEnabled(), d->text, foregroundRole()); } } else #ifndef QT_NO_PICTURE if (d->picture) { QRect br = d->picture->boundingRect(); int rw = br.width(); int rh = br.height(); if (d->scaledcontents) { painter.save(); painter.translate(cr.x(), cr.y()); painter.scale((double)cr.width()/rw, (double)cr.height()/rh); painter.drawPicture(-br.x(), -br.y(), *d->picture); painter.restore(); } else { int xo = 0; int yo = 0; if (align & Qt::AlignVCenter) yo = (cr.height()-rh)/2; else if (align & Qt::AlignBottom) yo = cr.height()-rh; if (align & Qt::AlignRight) xo = cr.width()-rw; else if (align & Qt::AlignHCenter) xo = (cr.width()-rw)/2; painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture); } } else #endif if (d->pixmap && !d->pixmap->isNull()) { QPixmap pix; if (d->scaledcontents) { if (!d->scaledpixmap || d->scaledpixmap->size() != cr.size()) { if (!d->cachedimage) d->cachedimage = new QImage(d->pixmap->toImage()); delete d->scaledpixmap; d->scaledpixmap = new QPixmap(QPixmap::fromImage(d->cachedimage->scaled(cr.size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation))); } pix = *d->scaledpixmap; } else pix = *d->pixmap; QStyleOption opt; opt.initFrom(this); if (!isEnabled()) pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt); style->drawItemPixmap(&painter, cr, align, pix); } }
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (!index.isValid()) { return; } bool mouseOver = option.state & QStyle::State_MouseOver; bool gtk = mouseOver && qApp->style()->inherits("QGtkStyle"); bool selected = option.state & QStyle::State_Selected; bool drawBgnd = true; if (!underMouse) { if (mouseOver && !selected) { drawBgnd = false; } mouseOver = false; } const QString text = index.model()->data(index, Qt::DisplayRole).toString(); const QIcon icon = index.model()->data(index, Qt::DecorationRole).value<QIcon>(); const QPixmap pixmap = icon.pixmap(iconSize, iconSize); QFontMetrics fm = painter->fontMetrics(); int wp = pixmap.width(); int hp = pixmap.height(); QTextLayout iconTextLayout(text, option.font); QTextOption textOption(Qt::AlignHCenter); iconTextLayout.setTextOption(textOption); int maxWidth = qMax(3 * wp, 8 * fm.height()); layoutText(&iconTextLayout, maxWidth); QPen pen = painter->pen(); QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if (cg == QPalette::Normal && !(option.state & QStyle::State_Active)) { cg = QPalette::Inactive; } QStyleOptionViewItem opt(option); opt.showDecorationSelected = true; QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); if (drawBgnd) { if (mouseOver && gtk) { painter->save(); opt.state |= QStyle::State_Selected; painter->setOpacity(selected ? 0.75 : 0.25); } style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); if (mouseOver && gtk) { painter->restore(); } } if (selected) { painter->setPen(option.palette.color(cg, QPalette::HighlightedText)); } else { painter->setPen(option.palette.color(cg, QPalette::Text)); } painter->drawPixmap(option.rect.x() + (option.rect.width() / 2) - (wp / 2), option.rect.y() + 5, pixmap); if (!text.isEmpty()) { iconTextLayout.draw(painter, QPoint(option.rect.x() + (option.rect.width() / 2) - (maxWidth / 2), option.rect.y() + hp + 7)); } painter->setPen(pen); drawFocus(painter, option, option.rect); }
TEST(ErrorBlockTests, error_blocks_maxwell) { ros::NodeHandle nh("~"); robot_calibration::Optimizer opt(robot_description); std::vector<robot_calibration_msgs::CalibrationData> data; robot_calibration_msgs::CalibrationData msg; // Match expected output from chain manager msg.joint_states.name.resize(10); msg.joint_states.name[0] = "arm_lift_joint"; msg.joint_states.name[1] = "arm_shoulder_pan_joint"; msg.joint_states.name[2] = "arm_shoulder_lift_joint"; msg.joint_states.name[3] = "arm_upperarm_roll_joint"; msg.joint_states.name[4] = "arm_elbow_flex_joint"; msg.joint_states.name[5] = "arm_wrist_flex_joint"; msg.joint_states.name[6] = "arm_wrist_roll_joint"; msg.joint_states.name[7] = "head_pan_joint"; msg.joint_states.name[8] = "head_tilt_joint"; msg.joint_states.name[9] = "arm_lift_joint"; msg.joint_states.position.resize(10); msg.joint_states.position[0] = -0.05; // Add some error msg.joint_states.position[1] = -0.814830; msg.joint_states.position[2] = -0.00022290000000002586; msg.joint_states.position[3] = 0.0; msg.joint_states.position[4] = -0.7087341; msg.joint_states.position[5] = 0.0; msg.joint_states.position[6] = 0.0; msg.joint_states.position[7] = -0.8280187999999999; msg.joint_states.position[8] = 0.6358500000000002; msg.joint_states.position[9] = 0.0; // Expectect output from led finder msg.observations.resize(2); msg.observations[0].sensor_name = "camera"; msg.observations[1].sensor_name = "arm"; msg.observations[0].features.resize(1); msg.observations[0].features[0].header.frame_id = "head_camera_rgb_optical_frame"; msg.observations[0].features[0].point.x = -0.0143163670728; msg.observations[0].features[0].point.y = 0.111304592065; msg.observations[0].features[0].point.z = 0.522079317365; msg.observations[0].ext_camera_info.camera_info.P[0] = 100.0; // fx msg.observations[0].ext_camera_info.camera_info.P[5] = 100.0; // fy msg.observations[0].ext_camera_info.camera_info.P[2] = 320.0; // cx msg.observations[0].ext_camera_info.camera_info.P[6] = 240.0; // cy msg.observations[0].ext_camera_info.parameters.resize(2); msg.observations[0].ext_camera_info.parameters[0].name = "z_offset"; msg.observations[0].ext_camera_info.parameters[0].value = 0.0; msg.observations[0].ext_camera_info.parameters[1].name = "z_scaling"; msg.observations[0].ext_camera_info.parameters[1].value = 1.0; msg.observations[1].features.resize(1); msg.observations[1].features[0].header.frame_id = "gripper_led_frame"; msg.observations[1].features[0].point.x = 0.0; msg.observations[1].features[0].point.y = 0.0; msg.observations[1].features[0].point.z = 0.0; // Add first data point data.push_back(msg); // Add a second data point that is just a little different msg.joint_states.position[1] = -0.019781999999999966; msg.joint_states.position[7] = 0.0; msg.observations[0].features[0].point.x = 0.0365330705881; msg.observations[0].features[0].point.y = 0.102609552493; msg.observations[0].features[0].point.z = 0.536061220027; data.push_back(msg); // And a third data point msg.joint_states.position[1] = 0.883596; msg.joint_states.position[7] = 0.9442135999999999; msg.observations[0].features[0].point.x = 0.0942445346646; msg.observations[0].features[0].point.y = 0.11409172323; msg.observations[0].features[0].point.z = 0.517497963716; data.push_back(msg); // Setup params robot_calibration::OptimizationParams params; params.LoadFromROS(nh); // Optimize opt.optimize(params, data, false); EXPECT_GT(opt.summary()->initial_cost, 0.001); EXPECT_LT(opt.summary()->final_cost, 1e-18); EXPECT_GT(opt.summary()->iterations.size(), static_cast<size_t>(1)); // expect more than 1 iteration // The -0.05 we added above should be calibrated off EXPECT_LT(fabs(0.05 - opt.getOffsets()->get("arm_lift_joint")), 0.001); // 1 joint EXPECT_EQ(1, opt.getNumParameters()); // 3 CalibrationData, each with chain3d with a single observed point (3 residuals) EXPECT_EQ(9, opt.getNumResiduals()); }
void FQTermShortcutHelper::initShortcutDescriptionTable() { initShortcutDescriptionTableEntry(CONNECT, "connect", tr(""), tr("Connect Host"), "connect"); initShortcutDescriptionTableEntry(CASCADEWINDOWS, "cascadewindows", tr(""), tr("Cascade Windows")); initShortcutDescriptionTableEntry(TILEWINDOWS, "tilewindows", tr(""), tr("Tils Windows")); initShortcutDescriptionTableEntry(DISCONNECT, "disconnect", tr(""), tr("Disconnect Host"), "disconnect"); initShortcutDescriptionTableEntry(ADDRESSBOOK, "addressbook", tr("F2"), tr("Address Book"), "address_book"); initShortcutDescriptionTableEntry(QUICKLOGIN, "quicklogin", tr("F3"), tr("Quick Login"), "quick_login"); #if defined(__APPLE__) initShortcutDescriptionTableEntry(COPY, "copy", tr("Ctrl+C"), tr("Copy"), "copy"); initShortcutDescriptionTableEntry(PASTE, "paste", tr("Ctrl+V"), tr("Paste"), "paste"); #else initShortcutDescriptionTableEntry(COPY, "copy", tr("Ctrl+Ins"), tr("Copy"), "copy"); initShortcutDescriptionTableEntry(PASTE, "paste", tr("Shift+Insert"), tr("Paste"), "paste"); #endif initShortcutDescriptionTableEntry(COPYWITHCOLOR, "copywithcolor", tr(""), tr("Copy With Color"), "copy_with_color"); getAction(COPYWITHCOLOR)->setCheckable(true); initShortcutDescriptionTableEntry(RECTANGLESELECTION, "rectangleselection", tr(""), tr("Rectangle Selection"), "rectangle_selection"); getAction(RECTANGLESELECTION)->setCheckable(true); initShortcutDescriptionTableEntry(AUTOCOPYSELECTION, "autocopyselection", tr(""), tr("Auto Copy Selection")); getAction(AUTOCOPYSELECTION)->setCheckable(true); initShortcutDescriptionTableEntry(PASTEWORDWRAP, "pastewordwrap", tr(""), tr("Paste With Word Wrap")); getAction(PASTEWORDWRAP)->setCheckable(true); initShortcutDescriptionTableEntry(ENGLISHFONT, "englishfont", tr(""), tr("Set English Font")); initShortcutDescriptionTableEntry(OTHERFONT, "nonenglishfont", tr(""), tr("Set Other Font")); initShortcutDescriptionTableEntry(COLORSETTING, "colorsetting", tr(""), tr("Color Setting"), "ansi_color"); initShortcutDescriptionTableEntry(REFRESHSCREEN, "refreshscreen", tr(""), tr("Refresh Screen"), "refresh"); initShortcutDescriptionTableEntry(ANSICOLOR, "ansicolor", tr(""), tr("Toggle Ansi Color"), "toggle_ansi_color"); getAction(ANSICOLOR)->setCheckable(true); initShortcutDescriptionTableEntry(UIFONT, "uifont", tr(""), tr("Set UI Font")); initShortcutDescriptionTableEntry(FULLSCREEN, "fullscreen", tr("F6"), tr("Toggle Full Screen")); getAction(FULLSCREEN)->setCheckable(true); initShortcutDescriptionTableEntry(BOSSCOLOR, "bosscolor", tr("F12"), tr("Toggle Boss Color")); getAction(BOSSCOLOR)->setCheckable(true); initShortcutDescriptionTableEntry(SWITCHBAR, "switchbar", tr(""), tr("Toggle Switch Bar")); getAction(SWITCHBAR)->setCheckable(true); initShortcutDescriptionTableEntry(CURRENTSETTING, "currentsetting", tr(""), tr("Current Session Setting"), "preferences"); initShortcutDescriptionTableEntry(SEARCHIT, "googleit", tr("Ctrl+Alt+G"), tr("Google selected words")); initShortcutDescriptionTableEntry(WEIBOSHARE, "shareit", tr("Alt+`"), tr("Share selected text and highlighted URL to weibo")); initShortcutDescriptionTableEntry(EXTERNALEDITOR, "externaleditor", tr("Ctrl+Alt+E"), tr("Invoke external editor")); initShortcutDescriptionTableEntry(FASTPOST, "fastpost", tr("Ctrl+Alt+F"), tr("Fast post from clipboard")); initShortcutDescriptionTableEntry(DEFAULTSETTING, "defaultsetting", tr(""), tr("Default Setting")); initShortcutDescriptionTableEntry(PREFERENCE, "preference", tr(""), tr("Preference"), "preferences"); initShortcutDescriptionTableEntry(EDITSCHEMA, "schema", tr(""), tr("Edit Schema")); initShortcutDescriptionTableEntry(SHORTCUTSETTING, "shortcut", tr(""), tr("Shorcut Setting")); initShortcutDescriptionTableEntry(COPYARTICLE, "copyarticle", tr("F9"), tr("Copy Article"), "get_article_fulltext"); initShortcutDescriptionTableEntry(ANTIIDLE, "antiidle", tr(""), tr("Toggle Anti Idle"), "anti_idle"); getAction(ANTIIDLE)->setCheckable(true); initShortcutDescriptionTableEntry(AUTOREPLY, "autoreply", tr(""), tr("Toggle Auto Reply"), "auto_reply"); getAction(AUTOREPLY)->setCheckable(true); initShortcutDescriptionTableEntry(VIEWMESSAGE, "viewmessage", tr("F10"), tr("View Messages"), "view_messages"); initShortcutDescriptionTableEntry(IPLOOKUP, "iplookup", tr(""), tr("IP Lookup")); initShortcutDescriptionTableEntry(BEEP, "beep", tr(""), tr("Toggle Beep"), "beep"); getAction(BEEP)->setCheckable(true); initShortcutDescriptionTableEntry(MOUSESUPPORT, "mousesupport", tr(""), tr("Toggle Mouse Support"), "mouse"); getAction(MOUSESUPPORT)->setCheckable(true); initShortcutDescriptionTableEntry(IMAGEVIEWER, "imageviewer", tr(""), tr("Image Viewer"), "image_viewer"); initShortcutDescriptionTableEntry(RUNSCRIPT, "runscript", tr("F7"), tr("Run Script")); initShortcutDescriptionTableEntry(STOPSCRIPT, "stop", tr("F8"), tr("Stop Script")); #ifdef HAVE_PYTHON initShortcutDescriptionTableEntry(RUNPYTHONSCRIPT, "runpythonscript", tr("Ctrl+F1"), tr("Run Python Script")); #endif //HAVE_PYTHON initShortcutDescriptionTableEntry(ABOUT, "about", tr("Shift+F1"), tr("About")); initShortcutDescriptionTableEntry(HOMEPAGE, "homepage", tr(""), tr("Homepage")); initShortcutDescriptionTableEntry(EXIT, "exit", tr(""), tr("Exit FQTerm")); initShortcutDescriptionTableEntry(COLORCTL_NO, "colorctlno", tr(""), tr("Set Color Ctrl to None")); getAction(COLORCTL_NO)->setCheckable(true); initShortcutDescriptionTableEntry(COLORCTL_SMTH, "colorctlsmth", tr(""), tr("Set Color Ctrl to **[")); getAction(COLORCTL_SMTH)->setCheckable(true); initShortcutDescriptionTableEntry(COLORCTL_PTT, "colorctlptt", tr(""), tr("Set Color Ctrl to ^u[")); getAction(COLORCTL_PTT)->setCheckable(true); initShortcutDescriptionTableEntry(COLORCTL_OLD_CUSTOM, "colorctloldcustom", tr(""), tr("Set Color Ctrl to old custom")); getAction(COLORCTL_OLD_CUSTOM)->setCheckable(true); initShortcutDescriptionTableEntry(COLORCTL_CUSTOM, "colorctlcustom", tr(""), tr("Set Color Ctrl to custom")); getAction(COLORCTL_CUSTOM)->setCheckable(false); initShortcutDescriptionTableEntry(AUTORECONNECT, "autoreconnect", tr(""), tr("Toggle Auto Reconnect"), "auto_reconnect"); getAction(AUTORECONNECT)->setCheckable(true); initShortcutDescriptionTableEntry(SCROLLBAR_LEFT, "scrollbarleft", tr(""), tr("Set Scrollbar to Left")); getAction(SCROLLBAR_LEFT)->setCheckable(true); initShortcutDescriptionTableEntry(SCROLLBAR_RIGHT, "scrollbarright", tr(""), tr("Set Scrollbar to Right")); getAction(SCROLLBAR_RIGHT)->setCheckable(true); initShortcutDescriptionTableEntry(SCROLLBAR_HIDDEN, "scrollbarhidden", tr(""), tr("Set Scrollbar Hidden")); getAction(SCROLLBAR_HIDDEN)->setCheckable(true); initShortcutDescriptionTableEntry(SEARCH_GOOGLE, "searchgoogle", tr(""), tr("Use Google")); getAction(SEARCH_GOOGLE)->setCheckable(true); initShortcutDescriptionTableEntry(SEARCH_BAIDU, "searchbaidu", tr(""), tr("Use Baidu")); getAction(SEARCH_BAIDU)->setCheckable(true); initShortcutDescriptionTableEntry(SEARCH_BING, "searchbing", tr(""), tr("Use Bing")); getAction(SEARCH_BING)->setCheckable(true); initShortcutDescriptionTableEntry(SEARCH_YAHOO, "searchyahoo", tr(""), tr("Use Yahoo!")); getAction(SEARCH_YAHOO)->setCheckable(true); initShortcutDescriptionTableEntry(SEARCH_CUSTOM, "searchcustom", tr(""), tr("Use Customized SE")); getAction(SEARCH_CUSTOM)->setCheckable(true); initShortcutDescriptionTableEntry(LANGUAGE_ENGLISH, "languageenglish", tr(""), tr("Choose UI Language: English")); getAction(LANGUAGE_ENGLISH)->setCheckable(true); initShortcutDescriptionTableEntry(SAVESETTING, "savesetting", tr(""), tr("Save Current Session Setting"), "save_setting"); #if defined(__APPLE__) QString opt(tr("Ctrl")); #else QString opt(tr("Alt")); #endif initShortcutDescriptionTableEntry(NEXTWINDOW, "nextwindow", opt + tr("+Right"), tr("Next Window")); initShortcutDescriptionTableEntry(PREVWINDOW, "prevwindow", opt + tr("+Left"), tr("Prev Window")); initShortcutDescriptionTableEntry(GLOBAL_SHOW_FQTERM, "showfqterm", tr("Ctrl+Alt+Q"), tr("Show FQTerm")); //index, key, default shortcut, descritption retranslateActions(); }
void ShowCounts::execute() { if ( d->state == 0 ) { parseOptions(); end(); database(); d->state = 1; EString s( Configuration::text( Configuration::DbSchema ) ); d->query = new Query( "select " "(select count(*) from users)::int as users," "(select count(*) from mailboxes where deleted='f')::int" " as mailboxes," "(" + tuples( "messages" ) + ")::int as messages," "(" + tuples( "bodyparts" ) + ")::int as bodyparts," "(" + tuples( "addresses" ) + ")::int as addresses," "(" + tuples( "deleted_messages" ) + ")::int as dm", this ); d->query->bind( 1, s ); d->query->execute(); } if ( d->state == 1 ) { if ( !d->query->done() ) return; Row * r = d->query->nextRow(); if ( d->query->failed() || !r ) error( "Couldn't fetch estimates." ); printf( "Users: %d\n", r->getInt( "users" ) ); printf( "Mailboxes: %d\n", r->getInt( "mailboxes" ) ); if ( opt( 'f' ) == 0 ) { printf( "Messages: %d", r->getInt( "messages" ) ); if ( r->getInt( "dm" ) != 0 ) printf( " (%d deleted)", r->getInt( "dm" ) ); printf( " (estimated)\n" ); printf( "Bodyparts: %d (estimated)\n", r->getInt( "bodyparts" ) ); printf( "Addresses: %d (estimated)\n", r->getInt( "addresses" ) ); d->state = 666; finish(); return; } d->query = new Query( "select count(*)::int as messages, " "coalesce(sum(rfc822size)::bigint,0) as totalsize, " "(select count(*) from mailbox_messages)::int " "as mm, " "(select count(*) from deleted_messages)::int " "as dm from messages", this ); d->query->execute(); d->state = 2; } if ( d->state == 2 ) { if ( !d->query->done() ) return; Row * r = d->query->nextRow(); if ( d->query->failed() || !r ) error( "Couldn't fetch messages/deleted_messages counts." ); int um = r->getInt( "messages" ); int mm = r->getInt( "mm" ); int dm = r->getInt( "dm" ); printf( "Messages: %d unique", um ); printf( " (%d in mailboxes", mm ); if ( dm != 0 ) printf( ", %d deleted", dm ); printf( ", total size: %s", EString::humanNumber( r->getBigint( "totalsize" ) ).cstr() ); printf( ")\n" ); d->query = new Query( "select count(*)::int as bodyparts," "coalesce(sum(length(text))::bigint,0) as textsize," "coalesce(sum(length(data))::bigint,0) as datasize " "from bodyparts", this ); d->query->execute(); d->state = 3; } if ( d->state == 3 ) { if ( !d->query->done() ) return; Row * r = d->query->nextRow(); if ( d->query->failed() || !r ) error( "Couldn't fetch bodyparts counts." ); printf( "Bodyparts: %d (text size: %s, data size: %s)\n", r->getInt( "bodyparts" ), EString::humanNumber( r->getBigint( "textsize" ) ).cstr(), EString::humanNumber( r->getBigint( "datasize" ) ).cstr() ); d->query = new Query( "select count(*)::int as addresses " "from addresses", this ); d->query->execute(); d->state = 4; } if ( d->state == 4 ) { if ( !d->query->done() ) return; Row * r = d->query->nextRow(); if ( d->query->failed() || !r ) error( "Couldn't fetch addresses counts." ); printf( "Addresses: %d\n", r->getInt( "addresses" ) ); d->state = 666; } finish(); }
int main(const int iArgc, const char** iArgv) { std::string rootDir; ConciseArgs opt(iArgc, (char**)iArgv); opt.add(rootDir, "r", "root_dir", "input root directory"); opt.parse(); // set up vo std::shared_ptr<drc::BotWrapper> botWrapper(new drc::BotWrapper()); std::shared_ptr<drc::LcmWrapper> lcmWrapper(new drc::LcmWrapper(botWrapper->getLcm())); auto boostLcm = lcmWrapper->getBoost(); auto config = new voconfig::KmclConfiguration(botWrapper->getBotParam(), "CAMERA"); boost::shared_ptr<fovis::StereoCalibration> calib(config->load_stereo_calibration()); FoVision vo(boostLcm, calib); // find file timestamps std::ifstream ifs(rootDir + "/cam_poses.txt"); std::vector<int64_t> times; std::string line; while (std::getline(ifs,line)) { std::istringstream iss(line); int64_t utime; iss >> utime; times.push_back(utime); } // iterate std::string poseFileName = rootDir + "/fovis_poses.txt"; std::ofstream ofs(poseFileName); ofs << std::setprecision(15); for (auto utime : times) { std::string fileName; std::ostringstream oss; // read image oss << rootDir << "/color_" << utime << ".png"; cv::Mat img = cv::imread(oss.str()); cv::cvtColor(img,img,CV_RGB2GRAY); // read disparity oss.str(""); oss.clear(); oss << rootDir << "/disp_" << utime << ".float"; std::ifstream ifs(oss.str(), std::ios::binary); int width, height; ifs.read((char*)&width, sizeof(width)); ifs.read((char*)&height, sizeof(height)); std::vector<float> vals(width*height); ifs.read((char*)vals.data(), width*height*sizeof(float)); ifs.close(); cv::Mat disp(height,width,CV_32FC1,vals.data()); // do fovis vo.doOdometry(img.data, (float*)disp.data, utime); Eigen::Isometry3d delta; auto worldToCamera = Eigen::Isometry3d::Identity(); Eigen::MatrixXd cov; fovis::MotionEstimateStatusCode status; vo.getMotion(delta, cov, status); worldToCamera = worldToCamera*delta; vo.fovis_stats(); // write pose auto cameraPose = worldToCamera.inverse(); auto& m = cameraPose; ofs << utime << " " << m(0,0) << " " << m(0,1) << " " << m(0,2) << " " << m(0,3) << " " << m(1,0) << " " << m(1,1) << " " << m(1,2) << " " << m(1,3) << " " << m(2,0) << " " << m(2,1) << " " << m(2,2) << " " << m(2,3) << std::endl; } ofs.close(); return 1; }
//-------------------------------------------------------------------------------------------------// void OSXCarbonWindow::create( const String& name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams ) { bool hasDepthBuffer = false; String title = name; size_t fsaa_samples = 0; int left = 0; int top = 0; bool vsync = false; bool hidden = false; int depth = 32; if( miscParams ) { NameValuePairList::const_iterator opt(NULL); NameValuePairList::const_iterator end = miscParams->end(); // Full screen anti aliasing if((opt = miscParams->find("FSAA")) != end) fsaa_samples = StringConverter::parseUnsignedInt( opt->second ); if((opt = miscParams->find("left")) != end) left = StringConverter::parseUnsignedInt( opt->second ); if((opt = miscParams->find("top")) != end) top = StringConverter::parseUnsignedInt( opt->second ); if((opt = miscParams->find("title")) != end) title = opt->second; if((opt = miscParams->find("vsync")) != end) vsync = StringConverter::parseBool(opt->second); if((opt = miscParams->find("hidden")) != end) hidden = StringConverter::parseBool(opt->second); if((opt = miscParams->find("gamma")) != end) mHwGamma = StringConverter::parseBool(opt->second); if((opt = miscParams->find("depthBuffer")) != end) hasDepthBuffer = StringConverter::parseBool( opt->second ); if((opt = miscParams->find("colourDepth")) != end) depth = StringConverter::parseUnsignedInt( opt->second ); if((opt = miscParams->find("Full Screen")) != end) fullScreen = StringConverter::parseBool( opt->second ); } if(fullScreen) { setFullscreen(fullScreen, width, height); } else { createAGLContext(fsaa_samples, depth); NameValuePairList::const_iterator opt(NULL); if(miscParams) opt = miscParams->find("externalWindowHandle"); if(!miscParams || opt == miscParams->end()) createNewWindow(width, height, title.c_str()); else createWindowFromExternal((HIViewRef)StringConverter::parseUnsignedLong(opt->second)); // Set the drawable, and current context // If you do this last, there is a moment before the rendering window pops-up // This could go once inside each case above, before the window is displayed, // if desired. #if defined(MAC_OS_X_VERSION_10_4) && MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4 aglSetDrawable(mAGLContext, GetWindowPort(mWindow)); #else aglSetWindowRef(mAGLContext, mWindow); #endif aglSetCurrentContext(mAGLContext); // Give a copy of our context to the render system if(!mCarbonContext) { mCarbonContext = OGRE_NEW OSXCarbonContext(mAGLContext, mAGLPixelFormat); mContext = mCarbonContext; } } // Apply vsync settings. call setVSyncInterval first to avoid // setting vsync more than once. setVSyncEnabled(vsync); setHidden(hidden); mName = name; mWidth = width; mHeight = height; mColourDepth = depth; mFSAA = fsaa_samples; mIsFullScreen = fullScreen; mActive = true; mClosed = false; mCreated = true; }
QPixmap QtopiaPicIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) { QString key = createKey(d->filename, size, mode, state, QApplication::palette().color(QPalette::Highlight)); QPixmap pm; // See if we have it in our local cache first. if (QPixmapCache::find(key, pm)) return pm; // Try explicitly added pixmaps if (d->pixmaps) { if (d->pixmaps->contains(key)) return d->pixmaps->value(key); } // Perhaps it has already been stored in the global cache. bool globalCandidate = false; if (size.height() == QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize) || size.height() == QApplication::style()->pixelMetric(QStyle::PM_TabBarIconSize) || size.height() == QApplication::style()->pixelMetric(QStyle::PM_LargeIconSize) || size.height() == QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize)) { if (QGlobalPixmapCache::find(key, pm)) { qLog(Resource) << "Icon found in global cache" << d->filename; // Put in local cache because we will probably use again soon. QPixmapCache::insert(key, pm); return pm; } globalCandidate = true; qLog(Resource) << "Icon not found in global cache" << d->filename; } if (!d->loaded) { if (!d->picture) d->picture = new QPicture; if (!d->picture->load(d->filename)) qWarning() << "Cannot load icon" << d->filename; else qLog(Resource) << "loaded pic icon" << d->filename; d->loaded = true; } QImage img(size, QImage::Format_ARGB32_Premultiplied); img.fill(0x00000000); QPainter p(&img); QRectF br = d->picture->boundingRect(); if (br.width() == 0 || br.height() == 0) return QPixmap(); if (br.width() > 0 && br.height() > 0) p.scale(qreal(size.width())/br.width(), qreal(size.height())/br.height()); p.drawPicture(0, 0, *d->picture); p.end(); pm = QPixmap::fromImage(img); QStyleOption opt(0); opt.palette = QApplication::palette(); QPixmap generated = QApplication::style()->generatedIconPixmap(mode, pm, &opt); if (!generated.isNull()) pm = generated; // We'll only put the standard icon sizes in the global cache because // there's a high likelyhood that they'll be used by others. if (globalCandidate) QGlobalPixmapCache::insert(key, pm); // Still worthwhile putting in the local cache since it is very likely // to be rendered again QPixmapCache::insert(key, pm); return pm; }
void QFrame::drawFrame(QPainter *p) { QPoint p1, p2; QRect r = frameRect(); int type = fstyle & MShape; int cstyle = fstyle & MShadow; #ifdef QT_NO_DRAWUTIL p->setPen(black); // #### p->drawRect(r); //### a bit too simple #else const QColorGroup & g = colorGroup(); #ifndef QT_NO_STYLE QStyleOption opt(lineWidth(), midLineWidth()); QStyle::SFlags flags = QStyle::Style_Default; if (isEnabled()) flags |= QStyle::Style_Enabled; if (cstyle == Sunken) flags |= QStyle::Style_Sunken; else if (cstyle == Raised) flags |= QStyle::Style_Raised; if (hasFocus()) flags |= QStyle::Style_HasFocus; if (hasMouse()) flags |= QStyle::Style_MouseOver; #endif // QT_NO_STYLE switch (type) { case Box: if (cstyle == Plain) qDrawPlainRect(p, r, g.foreground(), lwidth); else qDrawShadeRect(p, r, g, cstyle == Sunken, lwidth, midLineWidth()); break; case LineEditPanel: style().drawPrimitive(QStyle::PE_PanelLineEdit, p, r, g, flags, opt); break; case GroupBoxPanel: style().drawPrimitive(QStyle::PE_PanelGroupBox, p, r, g, flags, opt); break; case TabWidgetPanel: style().drawPrimitive(QStyle::PE_PanelTabWidget, p, r, g, flags, opt); break; case MenuBarPanel: #ifndef QT_NO_STYLE style().drawPrimitive(QStyle::PE_PanelMenuBar, p, r, g, flags, opt); break; #endif // fall through to Panel if QT_NO_STYLE case ToolBarPanel: #ifndef QT_NO_STYLE style().drawPrimitive(QStyle::PE_PanelDockWindow, p, rect(), g, flags, opt); break; #endif // fall through to Panel if QT_NO_STYLE case StyledPanel: #ifndef QT_NO_STYLE if (cstyle == Plain) qDrawPlainRect(p, r, g.foreground(), lwidth); else style().drawPrimitive(QStyle::PE_Panel, p, r, g, flags, opt); break; #endif // fall through to Panel if QT_NO_STYLE case PopupPanel: #ifndef QT_NO_STYLE { int vextra = style().pixelMetric(QStyle::PM_PopupMenuFrameVerticalExtra, this), hextra = style().pixelMetric(QStyle::PM_PopupMenuFrameHorizontalExtra, this); if (vextra > 0 || hextra > 0) { QRect fr = frameRect(); int fw = frameWidth(); if (vextra > 0) { style().drawControl(QStyle::CE_PopupMenuVerticalExtra, p, this, QRect(fr.x() + fw, fr.y() + fw, fr.width() - (fw*2), vextra), g, flags, opt); style().drawControl(QStyle::CE_PopupMenuVerticalExtra, p, this, QRect(fr.x() + fw, fr.bottom() - fw - vextra, fr.width() - (fw*2), vextra), g, flags, opt); } if (hextra > 0) { style().drawControl(QStyle::CE_PopupMenuHorizontalExtra, p, this, QRect(fr.x() + fw, fr.y() + fw + vextra, hextra, fr.height() - (fw*2) - vextra), g, flags, opt); style().drawControl(QStyle::CE_PopupMenuHorizontalExtra, p, this, QRect(fr.right() - fw - hextra, fr.y() + fw + vextra, hextra, fr.height() - (fw*2) - vextra), g, flags, opt); } } if (cstyle == Plain) qDrawPlainRect(p, r, g.foreground(), lwidth); else style().drawPrimitive(QStyle::PE_PanelPopup, p, r, g, flags, opt); break; } #endif // fall through to Panel if QT_NO_STYLE case Panel: if (cstyle == Plain) qDrawPlainRect(p, r, g.foreground(), lwidth); else qDrawShadePanel(p, r, g, cstyle == Sunken, lwidth); break; case WinPanel: if (cstyle == Plain) qDrawPlainRect(p, r, g.foreground(), wpwidth); else qDrawWinPanel(p, r, g, cstyle == Sunken); break; case HLine: case VLine: if (type == HLine) { p1 = QPoint(r.x(), r.height() / 2); p2 = QPoint(r.x() + r.width(), p1.y()); } else { p1 = QPoint(r.x() + r.width() / 2, 0); p2 = QPoint(p1.x(), r.height()); } if (cstyle == Plain) { QPen oldPen = p->pen(); p->setPen(QPen(g.foreground(), lwidth)); p->drawLine(p1, p2); p->setPen(oldPen); } else qDrawShadeLine(p, p1, p2, g, cstyle == Sunken, lwidth, midLineWidth()); break; }
Bool_t AddRsnEventComputations(Bool_t isMC, const char *options = "", const char *taskName = "RSNtask") { // ================================================================================================================== // == PRELIMINARY OPERATIONS ======================================================================================== // ================================================================================================================== // retrieve task from manager, using its name AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliRsnAnalysisTask *task = (AliRsnAnalysisTask*)mgr->GetTask(taskName); if (!task) { Error("RsnConfigMonitor", "Task not found"); return kFALSE; } TString opt(options); opt.ToUpper(); opt.ReplaceAll(" ", ""); Bool_t central = opt.Contains("CENT"); Bool_t peripheral = opt.Contains("PERI"); // ================================================================================================================== // == EVENT CUTS ==================================================================================================== // ================================================================================================================== // event cuts are added directly to a cutSet in the task // we create all and then add thos which are needed // primary vertex: // - 2nd argument --> |Vz| range // - 3rd argument --> minimum required number of contributors // - 4th argument --> tells if TPC stand-alone vertexes must be accepted // we switch on the check for pileup AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", 10.0, 0, kFALSE); cutVertex->SetCheckPileUp(kTRUE); // centrality: // - 2nd argument --> one of the centrality evaluation methods // - 3rd, 4th argument --> centrality ranges in percentile (0-10 for central, 60-70 for peripheral) AliRsnCutValue *cutCentrality = 0x0; if (central) cutCentrality = new AliRsnCutValue("cutCentral", AliRsnValue::kEventCentralityV0, 0.0, 10.0); else if (peripheral) cutCentrality = new AliRsnCutValue("cutPeripheral", AliRsnValue::kEventCentralityV0, 60.0, 70.0); // primary vertex is always used task->GetEventCuts()->AddCut(cutVertex); // set cut scheme as AND of primary vertex and centrality, if initialized if (cutCentrality) { task->GetEventCuts()->AddCut(cutCentrality); task->GetEventCuts()->SetCutScheme(Form("%s & %s", cutVertex->GetName(), cutCentrality->GetName())); } else { task->GetEventCuts()->SetCutScheme(cutVertex->GetName()); } ::Info("AddEventStuff", "Scheme for event cuts: %s", task->GetEventCuts()->GetCutScheme().Data()); // ================================================================================================================== // == EVENT FUNCTIONS =============================================================================================== // ================================================================================================================== // we want to add an AliRsnFunction to compute multiplicity distribution // it is needed in order to know how many events we have in each multiplicity bin // axes AliRsnValue *axisEvMultSPD = new AliRsnValue("MultSPD", AliRsnValue::kEventMultSPD, 0.0, 150.0, 1.0); AliRsnValue *axisEvMultMC = new AliRsnValue("MultMC" , AliRsnValue::kEventMultMC , 0.0, 150.0, 1.0); // create function and add axis AliRsnFunction *fcnEv = new AliRsnFunction; if (!fcnEv->AddAxis(axisEvMultSPD)) return kFALSE; if (isMC && !fcnEv->AddAxis(axisEvMultMC)) return kFALSE; // add functions to pairs task->GetInfo()->AddEventFunction(fcnEv); return kTRUE; }
int main(int argc, char* argv[]) { TlGetopt opt(argc, argv, "hv"); if (opt["h"] == "defined") { showHelp(opt[0]); return EXIT_SUCCESS; } const bool bVerbose = (opt["v"] == "defined"); if (opt.getCount() <= 1) { showHelp(opt[0]); return EXIT_FAILURE; } const std::string inputMatrixPath1 = opt[1]; const std::string inputMatrixPath2 = opt[2]; const std::string outputMatrixPath = opt[3]; if (bVerbose == true) { std::cerr << "load matrix: " << inputMatrixPath1 << std::endl; } TlDenseGeneralMatrix_Lapack A; if (TlMatrixUtils::isLoadable(inputMatrixPath1, TlMatrixObject::CSFD)) { A.load(inputMatrixPath1); } else if (TlMatrixUtils::isLoadable(inputMatrixPath1, TlMatrixObject::RLHD)) { TlDenseSymmetricMatrix_Lapack tmp; tmp.load(inputMatrixPath1); A = tmp; } else { std::cerr << "can not open file: " << inputMatrixPath1 << std::endl; return EXIT_FAILURE; } if (bVerbose == true) { std::cerr << "load matrix: " << inputMatrixPath2 << std::endl; } TlDenseGeneralMatrix_Lapack B; if (TlMatrixUtils::isLoadable(inputMatrixPath2, TlMatrixObject::CSFD)) { B.load(inputMatrixPath2); } else if (TlMatrixUtils::isLoadable(inputMatrixPath2, TlMatrixObject::RLHD)) { TlDenseSymmetricMatrix_Lapack tmp; tmp.load(inputMatrixPath2); B = tmp; } else { std::cerr << "can not open file: " << inputMatrixPath2 << std::endl; return EXIT_FAILURE; } if (bVerbose == true) { std::cerr << "running..." << std::endl; } A.dotInPlace(B); if (bVerbose == true) { std::cerr << "save matrix: " << outputMatrixPath << std::endl; } if (outputMatrixPath != "") { A.save(outputMatrixPath); } return EXIT_SUCCESS; }
void ViewerNode::setZoomComboBoxText(const std::string& text) { ChoiceOption opt(text, "", ""); _imp->zoomChoiceKnob.lock()->setActiveEntry(opt, ViewSetSpec(0), eValueChangedReasonPluginEdited); }
/** * Run an fwd simulation optimization */ int main() { try { ////////////////////////////////////////////////////////////////////////////////////////////// //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%// ////////////////////////////////////////////////////////////////////////////////////////////// SimTools* simtools = new SimTools(); // Instance of simtools class to use my functions string osim_filename = ""; string force_filename_flex = ""; string marker_filename_flex = ""; string ik_setup_filename_flex = ""; string force_filename_ext = ""; string marker_filename_ext = ""; string ik_setup_filename_ext = ""; // Set up file directories // Define osim file location string osim_fd = "T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version9/"; // Specify force and trc mocap file string fd = "T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Lamb2 data files/"; osim_filename = osim_filename.append(osim_fd).append("Version9_contrained.osim"); // for flex //Open existing XML model Model osimModel(osim_filename); Model osimModelE(osim_filename); osimModel.printBasicInfo(cout); //FLEXION string expt_file_flex = "l2flexv2"; string output_fd_flex = "T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version9/flex_output.sto"; double tiFlex,tfFlex; tiFlex = 2; // Static equilibrium tfFlex = 15; // EXTENSION string expt_file_ext = "l2extv2a"; string output_fd_ext = "T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version9/ext_output.sto"; double tiExt,tfExt; tiExt = 5; tfExt = 18; //flex filenames force_filename_flex = force_filename_flex.append(fd).append(expt_file_flex).append(".mot"); marker_filename_flex = marker_filename_flex.append(fd).append(expt_file_flex).append(".trc"); ik_setup_filename_flex = ik_setup_filename_flex.append(osim_fd).append(expt_file_flex).append("_initial_ik.xml"); //ext filenames force_filename_ext = force_filename_ext.append(fd).append(expt_file_ext).append(".mot"); marker_filename_ext = marker_filename_ext.append(fd).append(expt_file_ext).append(".trc"); ik_setup_filename_ext = ik_setup_filename_ext.append(osim_fd).append(expt_file_ext).append("_initial_ik.xml"); // Create storage object for force file OpenSim::Storage* force_storage_ext = new Storage(force_filename_ext); OpenSim::Storage* force_storage_flex = new Storage(force_filename_flex); // smooths out all data.... force_storage_flex->smoothSpline(3,1); // order = 3, cutoff freq = 1Hz force_storage_flex->resampleLinear(0.1); // resample to 10Hz force_storage_ext->smoothSpline(3,1); // order = 3, cutoff freq = 1Hz force_storage_ext->resampleLinear(0.1); // resample to 10Hz //force_storage->print("T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version4/force_flex_smooth.sto"); ////////////////////////////////////////////////////////////////////////////////////////////// //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%// ////////////////////////////////////////////////////////////////////////////////////////////// //OpenSim::CoordinateSet& CS = osimModel.updCoordinateSet(); // Run initial ik step to find Initial conditions for forward simulation Array<double> ICs_Flex, ICs_Ext; osimModel.updCoordinateSet().get("t2ToGND_FE").setDefaultValue(0); // to flip up model so initial ik guess is close osimModel.updCoordinateSet().get("t2ToGND_LB").setDefaultValue(0); ICs_Ext = simtools->ik_constrain_torso(osimModel,marker_filename_ext,ik_setup_filename_ext,tiExt,tfExt); cout<<"\n\next ic: :"<<ICs_Ext<<endl; osimModel.print("T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version9/test1.osim"); OpenSim::CoordinateSet& CS = osimModel.updCoordinateSet();//.get("t2ToGND_FE").setDefaultIsPrescribed(false); for(int i = 0; i<6; i++) { // First 6 coordinates in cooridnate set correspond to rotx,roty,rotz,tx,ty,tz CS[i].setDefaultIsPrescribed(false); CS[i].setDefaultValue(0.0); } // For Flex osimModel.updCoordinateSet().get("t2ToGND_FE").setDefaultValue(-Pi/2); // to flip up model so initial ik guess is close osimModel.updCoordinateSet().get("t2ToGND_LB").setDefaultValue(-Pi/2); osimModel.print("T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version9/testa.osim"); // Returns state values at initial time -> ICs has length of coordinate set (computed by single ik step) ICs_Flex = simtools->ik_constrain_torso(osimModel,marker_filename_flex,ik_setup_filename_flex,tiFlex,tfFlex); osimModel.print("T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version9/test.osim"); cout<<"\n\nflex ic: :"<<ICs_Flex<<endl; // Set up point kinematic analyses -> to track marker positions for use in objective function //AnalysisSet pk_set = //simtools->AddPKAtest(osimModel); //cout<<"name : "<<osimModel.getNumAnalyses(); //cout<<"\n\nname : "<<osimModel.updAnalysisSet().get("m1"); ////// USE force file to prescribe forces to head_markers body ////simtools->ApplyForce(*force_storage_flex,osimModel); // Create measurement data structure for each simulation // // Open trc file and store in class MarkerData MarkerData md_flex = OpenSim::MarkerData(marker_filename_flex); MarkerData md_ext = OpenSim::MarkerData(marker_filename_ext); // Create storage object with marker data (md) in it Storage data_trc_flex, data_trc_ext; md_flex.makeRdStorage(data_trc_flex); md_ext.makeRdStorage(data_trc_ext); // crop storage object to only include data in time frame of simulation data_trc_flex.crop(tiFlex,tfFlex); // -> data_trc is used to calculate rms error between model marker and motion capture markers data_trc_ext.crop(tiExt,tfExt); // -> data_trc is used to calculate rms error between model marker and motion capture markers //osimModel.print("T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version9/test.osim"); //////////////////////////////////////////////////////////////////////////////////////////////// ////%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%// //////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // Create list of point kinematics reporters which match marker positions from osim model PointKinematics* m1h = new PointKinematics(&osimModel); PointKinematics* m2h = new PointKinematics(&osimModel); PointKinematics* m3h = new PointKinematics(&osimModel); PointKinematics* m4h = new PointKinematics(&osimModel); PointKinematics* m5h = new PointKinematics(&osimModel); PointKinematics* m6h = new PointKinematics(&osimModel); // points in head_marker ref frame specified by inspection Vec3 p1(0.071700000,0.00000000,-0.054772000); Vec3 p2(-0.071700000,0.00000000,-0.038524000); Vec3 p3(0.071700000,0.00000000,0.005228); Vec3 p4(-0.0300000,0.00000000,0.026928); Vec3 p5(0.0300000,0.00000000,0.026928); Vec3 p6(-0.071700000,0.00000000,-0.008524000); m1h->setBodyPoint("head_markers",p1); m2h->setBodyPoint("head_markers",p2); m3h->setBodyPoint("head_markers",p3); m4h->setBodyPoint("head_markers",p4); m5h->setBodyPoint("head_markers",p5); m6h->setBodyPoint("head_markers",p6); m1h->setRelativeToBody(&osimModel.updBodySet().get("ground")); m2h->setRelativeToBody(&osimModel.updBodySet().get("ground")); m3h->setRelativeToBody(&osimModel.updBodySet().get("ground")); m4h->setRelativeToBody(&osimModel.updBodySet().get("ground")); m5h->setRelativeToBody(&osimModel.updBodySet().get("ground")); m6h->setRelativeToBody(&osimModel.updBodySet().get("ground")); m1h->setName("m1"); m2h->setName("m2"); m3h->setName("m3"); m4h->setName("m4"); m5h->setName("m5"); m6h->setName("m6"); osimModel.addAnalysis(m1h); osimModel.addAnalysis(m2h); osimModel.addAnalysis(m3h); osimModel.addAnalysis(m4h); osimModel.addAnalysis(m5h); osimModel.addAnalysis(m6h); ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //// RUN SIMULATION for a given set of bushing force properties //// Define bushing properties //// Define translational stiffness (t_stiff - x,y,z), rotational stiffness (r_stiff - x,y,z) and corresponding damping Vec3 t_stiff(0),r_stiff(0.01),t_damp(0),r_damp(10); //// initialise vector of initial parameter guesses //int numParams = 4; //Vector guess(numParams); //guess[0] = 6.82;//6.00553; // theta star (degrees) //guess[1] = 1.22; // k1 (N*m/degree) //guess[2] = 7.29; // k2 (N*m/degree) //guess[3] = 0.22;//0.409055; // damping (Nm/(deg/sec)) //Vector PARAMS(numParams); //for (int i = 0; i<numParams; i++){ // PARAMS[i] = guess[i]; //} ////string fd = ""; //simtools->RunSimulation_FlexExt(osimModel,PARAMS,tiFlex,tiExt,tfFlex,tfExt,ICs_Flex,ICs_Ext,false,fd,*force_storage_flex,*force_storage_ext,*m1h,*m2h,*m3h,*m4h,*m5h,*m6h,data_trc_flex,data_trc_ext); // // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // //// Initialise and run optimization int numParams = 5; //// Parameters: //// - Theta_STAR //// - k1 //// - k2 //// - damping //MyOptimizerSystem sys(numParams,osimModel,data_trc,ti,tf,ICs,*m1h,*m2h,*m3h,*m4h,*m5h,*m6h,output_fd); MyOptimizerSystem sys(numParams,osimModel,tiFlex,tiExt,tfFlex,tfExt,ICs_Flex,ICs_Ext,*force_storage_flex,*force_storage_ext,*m1h,*m2h,*m3h,*m4h,*m5h,*m6h,data_trc_flex,data_trc_ext); Real f = NaN; Vector lower_bounds(numParams); Vector upper_bounds(numParams); // theta star flex lower_bounds[0] = 2;//0.0;//*Pi/180; upper_bounds[0] = 12;//1.0;//*Pi/180; // theta star ext lower_bounds[1] = 2;//0.0;//*Pi/180; upper_bounds[1] = 12;//1.0;//*Pi/180; // k1 lower_bounds[2] = 1e-6;//0.0;//*Pi/180; upper_bounds[2] = 15;//1.0;//*Pi/180; // k2 lower_bounds[3] = 0.1; upper_bounds[3] = 100; // damping lower_bounds[4] = -2; upper_bounds[4] = 2; //head mass //lower_bounds[3] = -2.0; //upper_bounds[3] = 2.0; //// theta star sk //lower_bounds[4] = 6;//0.0;//*Pi/180; //upper_bounds[4] = 30;//1.0;//*Pi/180; //// k1 sk //lower_bounds[5] = 1e-6;//0.0;//*Pi/180; //upper_bounds[5] = 15;//1.0;//*Pi/180; //// k2 sk //lower_bounds[6] = 0.1; //upper_bounds[6] = 100; // set parameter limits sys.setParameterLimits(lower_bounds,upper_bounds); // initialise vector of initial parameter guesses Vector guess(numParams); guess[0] = 6.82; //flexion theta star (degrees) guess[1] = 6.82; // extension theta star (degrees) guess[2] = 1.22; // k1 (N*m/degree) guess[3] = 7.29; // k2 (N*m/degree) guess[4] = 0.3; // bushing offset //guess[4] = 0.0; // head mass // guess[4] = 45; // theta star sk (degrees) //guess[5] = guess[1]; // k1 sk (N*m/degree) //guess[6] = guess[2]; // k2 sk (N*m/degree) // Try optimisation clock_t t1,t2,t3,t4; t1 = clock(); try{ // intialise optimizer Optimizer opt(sys, SimTK::InteriorPoint); opt.setDiagnosticsLevel(5); // Optimisation settings opt.setConvergenceTolerance(1e-3); opt.setMaxIterations(1000); opt.useNumericalGradient(true); opt.setLimitedMemoryHistory(500); // return optimum solution f = opt.optimize(guess); cout<<"\nf = "<<f; cout<<"\nguess = "<<guess; } catch(const std::exception& e) { std::cout << "OptimizationExample.cpp Caught exception :" << std::endl; std::cout << e.what() << std::endl; } t2 = clock(); //// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // //cout<<"\n\nOptimiszation time: "<<((float)t2-(float)t1)/ CLOCKS_PER_SEC << " seconds"; // //// Run simulation and save point kinematic reporter in data_sim storage object. Print simulation results to file. //Array<Array<double>> pk_data; Vector PARAMS(numParams); for (int i = 0; i<numParams; i++){ PARAMS[i] = guess[i]; } //string fd = ""; simtools->RunSimulation_FlexExt(osimModel,PARAMS,tiFlex,tiExt,tfFlex,tfExt,ICs_Flex,ICs_Ext,false,fd,*force_storage_flex,*force_storage_ext,*m1h,*m2h,*m3h,*m4h,*m5h,*m6h,data_trc_flex,data_trc_ext); //// //////cout<<"\n\npk_data: "<<pk_data; ////t3 = clock(); ////cout<<"\n\nSimulation time: "<<((float)t3-(float)t2)/ CLOCKS_PER_SEC << " seconds"; ////double rms = simtools->Calc_rms_VERSION2(data_trc,ti,tf,pk_data); ////t4 = clock(); ////cout<<"\n\nRMS time: "<<((float)t4-(float)t3)/ CLOCKS_PER_SEC << " seconds"; ////cout<<"\n\nRMS ERROR: "<<rms; //// ////osimModel.print("T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version5/test.osim"); ////ofstream myfile; ////myfile.open("T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version6/Model/fileConstrainedwBushingAndLimit.txt"); ////double rms = 0; ////int n = 25; ////double val = 0; ////Vector k(n,(double)0); ////Vector obj(n,(double)0); ////for (int i=0; i<n; i++){ //// t1 = clock(); //// val = i*0.5 + 4; //// t_slackL_opt = val; //// //Vec3 r_stiff_opt(val); //// pk_data = simtools->RunSimulation_LIMITSTOP(osimModel,t_stiff,r_stiff_opt,t_damp,r_damp,ti,tf,t_slackL_opt,vert_mass_opt,head_mass_opt,ICs,false,osim_fd,*m1h,*m2h,*m3h,*m4h,*m5h,*m6h,fibreL_opt); //// rms = simtools->Calc_rms_VERSION2(data_trc,ti,tf,pk_data); //// k[i] = val; //// obj[i] = rms; //// cout<<i<<"\n"; //// myfile<<k[i]<<"\t"<<obj[i]<<"\n"; //// t2 = clock(); //// cout<<k[i]<<"\t"<<obj[i]<<"\n"; //// cout<<"\n\nLoop time: "<<((float)t2-(float)t1)/ CLOCKS_PER_SEC << " seconds"; ////} ////myfile.close(); ////cout<<"\n\nk = "<<k; ////cout<<"\n\nobj = "<<obj; // ////ofstream myfile_2param; ////myfile_2param.open("T:/Lamb expts 2012/Lamb experiments 2012/23rd - 24th July Expts/Opensim/Version6/Model/fileConstrainedwBushingAndLimit_2param_v2.txt"); ////double rms = 0; ////int n =10; ////int nn = 20; ////double val_k = 0, val_m = 0; ////Vector k(n*nn,(double)0); ////Vector m(n*nn,(double)0); ////Vector obj(n*nn,(double)0); ////for (int i=0; i<n; i++){ //// for (int j=0;j<nn; j++){ //// val_k = i*0.05 + 0.3; //// val_m = j*0.5 + 5; //// t_slackL_opt = val_m; //// head_mass_opt = val_k; //// //Vec3 r_stiff_opt(val_k); //// t_slackL_opt = val_m; //// pk_data = simtools->RunSimulation_LIMITSTOP(osimModel,t_stiff,r_stiff_opt,t_damp,r_damp,ti,tf,t_slackL_opt,vert_mass_opt,head_mass_opt,ICs,false,osim_fd,*m1h,*m2h,*m3h,*m4h,*m5h,*m6h,fibreL_opt); //// rms = simtools->Calc_rms_VERSION2(data_trc,ti,tf,pk_data); //// k[i*n + j] = val_k; //// m[i*n + j] = val_m; //// obj[i*n + j] = rms; //// cout<<(i)<<"\t"<<j<<"\n"; //// cout<<k[i*n + j]<<"\n"; //// cout<<m[i*n + j]<<"\n"; //// cout<<rms<<"\n"; //// myfile_2param<<k[i*n + j]<<"\t"<<m[i*n + j]<<"\t"<<obj[i*n + j]<<"\n"; //// } ////} ////myfile_2param.close(); ////cout<<"\n\nk = "<<k; ////cout<<"\n\nm = "<<m; ////cout<<"\n\nobj = "<<obj; //////////////////////////////////////////////////////////////////////////////////////////////// ////%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%// //////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } catch (OpenSim::Exception ex) { std::cout << ex.getMessage() << std::endl; return 1; } catch (std::exception ex) { std::cout << ex.what() << std::endl; return 1; } catch (...) { std::cout << "UNRECOGNIZED EXCEPTION" << std::endl; return 1; } //std::cout << "main() routine time = " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n"; std::cout << "\n\nOpenSim example completed successfully.\n"; std::cin.get(); return 0; }
// makes the string for getopt std::string CommandOption::toGetoptShortOption() const { std::string opt(1, shortOpt); if (optFlag == hasArgument) opt += ":"; return opt; }
main(int argc, char *argv[]) { int i, j, nf; progname = argv[0]; ac = argc + 50; av = alloc(ac*sizeof(char *)); if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, interrupt); if (signal(SIGTERM, SIG_IGN) != SIG_IGN) signal(SIGTERM, interrupt); #ifdef SIGHUP if (signal(SIGHUP, SIG_IGN) != SIG_IGN) signal(SIGHUP, interrupt); #endif if (getenv("TMP")) tempdir = getenv("TMP"); else if (getenv("TEMP")) tempdir = getenv("TEMP"); else if (getenv("TMPDIR")) tempdir = getenv("TMPDIR"); assert(tempdir); i = strlen(tempdir); for (; i > 0 && tempdir[i-1] == '/' || tempdir[i-1] == '\\'; i--) tempdir[i-1] = '\0'; if (argc <= 1) { help(); exit(0); } plist = append("-D__LCC__", 0); initinputs(); if (getenv("LCCDIR")) option(stringf("-lccdir=%s", getenv("LCCDIR"))); for (nf = 0, i = j = 1; i < argc; i++) { if (strcmp(argv[i], "-o") == 0) { if (++i < argc) { if (suffix(argv[i], suffixes, 2) >= 0) { error("-o would overwrite %s", argv[i]); exit(8); } outfile = argv[i]; continue; } else { error("unrecognized option `%s'", argv[i-1]); exit(8); } } else if (strcmp(argv[i], "-target") == 0) { if (argv[i+1] && *argv[i+1] != '-') i++; continue; } else if (*argv[i] == '-' && argv[i][1] != 'l') { opt(argv[i]); continue; } else if (*argv[i] != '-' && suffix(argv[i], suffixes, 3) >= 0) nf++; argv[j++] = argv[i]; } if ((cflag || Sflag) && outfile && nf != 1) { fprintf(stderr, "%s: -o %s ignored\n", progname, outfile); outfile = 0; } argv[j] = 0; for (i = 0; include[i]; i++) plist = append(include[i], plist); if (ilist) { List b = ilist; do { b = b->link; plist = append(b->str, plist); } while (b != ilist); } ilist = 0; for (i = 1; argv[i]; i++) if (strcmp(argv[i], "-l") == 0 && argv[i+1] && *argv[i+1] != '-') { /* -l file */ llist[1] = append(argv[i++], llist[1]); llist[1] = append(argv[i], llist[1]); } else if (*argv[i] == '-') opt(argv[i]); else { char *name = exists(argv[i]); if (name) { if (strcmp(name, argv[i]) != 0 || nf > 1 && suffix(name, suffixes, 3) >= 0) fprintf(stderr, "%s:\n", name); filename(name, 0); } else error("can't find `%s'", argv[i]); } if (errcnt == 0 && !Eflag && !Sflag && !cflag && llist[1]) { compose(ld, llist[0], llist[1], append(outfile ? outfile : concat("a", first(suffixes[4])), 0)); if (callsys(av)) errcnt++; } rm(rmlist); return errcnt ? EXIT_FAILURE : EXIT_SUCCESS; }
int main(int argc, char* argv[]) { TlGetopt opt(argc, argv, "ahp:vw:"); const bool isAtomIndexMode = (opt["a"] == "defined"); const bool isVerbose = (opt["v"] == "defined"); const bool isShowHelp = (opt["h"] == "defined"); std::string pdfparamPath = "pdfparam.mpac"; if (opt["p"].empty() != true) { pdfparamPath = opt["p"]; } std::string saveMpacPath = ""; if (opt["w"].empty() != true) { saveMpacPath = opt["w"]; } if (isShowHelp) { showHelp(); std::exit(0); } TlMsgPack mpac; if (isVerbose) { std::cerr << TlUtils::format("reading %s ...", pdfparamPath.c_str()); } mpac.load(pdfparamPath); TlSerializeData data = mpac.getSerializeData(); TlOrbitalInfo orbInfo(data["coordinates"], data["basis_set"]); const int numOfAOs = orbInfo.getNumOfOrbitals(); if (isVerbose == true) { std::cerr << "total atoms: " << orbInfo.getNumOfAtoms() << std::endl; std::cerr << "total orbitals: " << numOfAOs << std::endl; } const int numOfArgs = opt.getCount() - 1; // opt[0] means the name of this program. if (isAtomIndexMode == true) { if (numOfArgs == 0) { showHelp(); std::exit(1); } for (int i = 0; i < numOfArgs; ++i) { const int atomIndex = std::atoi(opt[i + 1].c_str()); std::cout << TlUtils::format(">>>> atom index: %d", atomIndex) << std::endl; for (int aoIndex = 0; aoIndex < numOfAOs; ++aoIndex) { if (atomIndex == orbInfo.getAtomIndex(aoIndex)) { printOrbInfo(orbInfo, aoIndex); } } } } else { std::vector<int> orbitals; if (numOfArgs == 0) { orbitals.resize(numOfAOs); for (int i = 0; i < numOfAOs; ++i) { orbitals[i] = i; } } else { for (int i = 0; i < numOfArgs; ++i) { const int orb = std::atoi(opt[i + 1].c_str()); orbitals.push_back(orb); } } const int numOfQueries = orbitals.size(); if (saveMpacPath.empty()) { for (int i = 0; i < numOfQueries; ++i) { const int orb = orbitals[i]; if (orb < numOfAOs) { printOrbInfo(orbInfo, orb); } } } else { TlSerializeData output; for (int i = 0; i < numOfQueries; ++i) { const int orb = orbitals[i]; if (orb < numOfAOs) { TlSerializeData entry; entry["atom_index"] = orbInfo.getAtomIndex(orb); entry["atomic_number"] = TlAtom::getElementNumber(orbInfo.getAtomName(orb)); entry["symbol"] = orbInfo.getAtomName(orb); const TlPosition pos = orbInfo.getPosition(orb); TlSerializeData xyz; xyz.pushBack(pos.x() / AU_BOHR); xyz.pushBack(pos.y() / AU_BOHR); xyz.pushBack(pos.z() / AU_BOHR); entry["xyz"] = xyz; entry["shell_type_id"] = orbInfo.getShellType(orb); entry["shell_type"] = TlUtils::format("%c", shellTypes[orbInfo.getShellType(orb)]); entry["basis_type_id"] = orbInfo.getBasisType(orb); entry["basis_type"] = std::string(angularMomentumTypes[orbInfo.getBasisType(orb)]); const int contractions = orbInfo.getCgtoContraction(orb); for (int c = 0; c < contractions; ++c) { TlSerializeData pGTO; pGTO["exp"] = orbInfo.getExponent(orb, c); pGTO["coef"] = orbInfo.getCoefficient(orb, c); entry["pGTOs"].pushBack(pGTO); } output[orb] = entry; } } TlMsgPack mpack(output); if (isVerbose) { std::cerr << TlUtils::format("output: %s", saveMpacPath.c_str()) << std::endl; } mpack.save(saveMpacPath); } } return EXIT_SUCCESS; }
void DTPatientListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { if (!index.isValid()) return; painter->save(); bool isMarked = index.data(MarkedRole).toBool(); bool caseSens = index.data(CaseSensRole).toBool(); QString lineFIO = index.data(FIORole).toString(); QStyleOptionViewItemV4 opt(option); initStyleOption(&opt, index); QStyle *style = opt.widget->style(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); // if (option.state & QStyle::State_Selected) // painter->setPen(QPen(option.palette.brush(QPalette::HighlightedText), 0)); QRect itemRect = option.rect.adjusted(10, 8, 0, 0); QPixmap pixmap = mInfo.pixmap( QSize(16, 16), option.state & QStyle::State_Selected ? QIcon::Selected : QIcon::Normal, isMarked ? QIcon::On : QIcon::Off); painter->drawPixmap(itemRect.topLeft(), pixmap ); itemRect = option.rect.adjusted(cTextLeftMargin, 2, -2, -2); QFont fnt = painter->font(); fnt.setBold(true); painter->setFont(fnt); drawHightlightText(painter, lineFIO.isEmpty() ? "(не заданы)" : lineFIO, lineFIO.isEmpty() ? "" : index.data(SearchFIORole).toString(), itemRect, caseSens ? Qt::CaseSensitive : Qt::CaseInsensitive, true); fnt.setBold(false); painter->setFont(fnt); // qDebug() << "DTPatientListDelegate::paint option.rect" << option.rect << " lineFIO" << lineFIO; if (isMarked) { QString str; QRect textRect(itemRect); textRect.setWidth(option.fontMetrics.width("0")*14); textRect.adjust(0,option.fontMetrics.height() + option.fontMetrics.height() / 2 ,0,0); painter->drawText(textRect, Qt::AlignTop | Qt::AlignRight, "Пол:"); textRect.adjust(0,option.fontMetrics.height() ,0,0); painter->drawText(textRect, Qt::AlignTop | Qt::AlignRight, "Дата рожд:"); textRect.adjust(0,option.fontMetrics.height() + option.fontMetrics.height() / 2 ,0,0); painter->drawText(textRect, Qt::AlignTop | Qt::AlignLeft, "Телефоны"); textRect.adjust(0,option.fontMetrics.height() ,0,0); painter->drawText(textRect, Qt::AlignTop | Qt::AlignRight, "Осн. телефон:"); textRect.adjust(0,option.fontMetrics.height() ,0,0); painter->drawText(textRect, Qt::AlignTop | Qt::AlignRight, "Доп. телефон:"); textRect.adjust(0,option.fontMetrics.height() ,0,0); painter->drawText(textRect, Qt::AlignTop | Qt::AlignRight, "Доп. телефон:"); textRect.adjust(0,option.fontMetrics.height() + option.fontMetrics.height() / 2 ,0,0); painter->drawText(textRect, Qt::AlignTop | Qt::AlignLeft, "Адрес"); textRect = option.rect.adjusted(cTextLeftMargin + option.fontMetrics.width("0")*15, 2, -2, -2); textRect.adjust(0,option.fontMetrics.height() + option.fontMetrics.height() / 2 ,0,0); str = index.data(GenderRole).toString(); drawHightlightText(painter, str.isEmpty() ? "(не задан)" : str, str.isEmpty() ? "" : index.data(SearchGenderRole).toString(), textRect, caseSens ? Qt::CaseSensitive : Qt::CaseInsensitive); textRect.adjust(0,option.fontMetrics.height()/*+ option.fontMetrics.height() / 2 */,0,0); str = index.data(BornDateRole).toString(); drawHightlightText(painter, str.isEmpty() ? "(не задана)" : str, str.isEmpty() ? "" : index.data(SearchBornDateRole).toString(), textRect, caseSens ? Qt::CaseSensitive : Qt::CaseInsensitive); textRect.adjust(0,option.fontMetrics.height() + option.fontMetrics.height() / 2 ,0,0); //painter->drawText(textRect, Qt::AlignTop | Qt::AlignLeft, "Телефоны"); textRect.adjust(0,option.fontMetrics.height()/*+ option.fontMetrics.height() / 2 */,0,0); str = index.data(Phone1Role).toString(); drawHightlightText(painter, str.isEmpty() ? "(не задан)" : str, str.isEmpty() ? "" : index.data(SearchPhone1Role).toString(), textRect, caseSens ? Qt::CaseSensitive : Qt::CaseInsensitive); textRect.adjust(0,option.fontMetrics.height()/*+ option.fontMetrics.height() / 2 */,0,0); str = index.data(Phone2Role).toString(); drawHightlightText(painter, str.isEmpty() ? "(не задан)" : str, str.isEmpty() ? "" : index.data(SearchPhone2Role).toString(), textRect, caseSens ? Qt::CaseSensitive : Qt::CaseInsensitive); textRect.adjust(0,option.fontMetrics.height()/*+ option.fontMetrics.height() / 2 */,0,0); str = index.data(Phone3Role).toString(); drawHightlightText(painter, str.isEmpty() ? "(не задан)" : str, str.isEmpty() ? "" : index.data(SearchPhone3Role).toString(), textRect, caseSens ? Qt::CaseSensitive : Qt::CaseInsensitive); textRect.adjust(0,option.fontMetrics.height()/*+ option.fontMetrics.height() / 2 */,0,0); // painter->drawText(textRect, Qt::AlignTop | Qt::AlignLeft, "Адрес"); textRect.adjust( -option.fontMetrics.width("0")*12, option.fontMetrics.height() + option.fontMetrics.height() / 2 ,0,0); textRect.setWidth(cTextWidth); str = index.data(AddrRole).toString(); drawHightlightText(painter, str.isEmpty() ? "(не задан)" : str, str.isEmpty() ? "" : index.data(SearchAddrRole).toString(), textRect, caseSens ? Qt::CaseSensitive : Qt::CaseInsensitive); itemRect = option.rect.adjusted(cTextLeftMargin / 2, 24, -2, -2); painter->setPen(QColor(Qt::lightGray)); painter->drawLine(itemRect.topLeft(),itemRect.bottomLeft()); painter->drawLine(itemRect.bottomLeft(), QPoint(itemRect.bottomLeft().x()+cTextWidth + (cTextLeftMargin / 2 ),itemRect.bottomLeft().y())); itemRect.adjust(0, option.fontMetrics.height() * 2 + option.fontMetrics.height() / 4 , 0, 0); painter->drawLine(itemRect.topLeft(), QPoint(itemRect.topLeft().x()+cTextWidth + (cTextLeftMargin / 2 ),itemRect.topLeft().y())); itemRect.adjust(0, option.fontMetrics.height() * 4 + option.fontMetrics.height() / 2, 0, 0); painter->drawLine(itemRect.topLeft(), QPoint(itemRect.topLeft().x()+cTextWidth + (cTextLeftMargin / 2 ),itemRect.topLeft().y())); } else { QString linePhone = index.data(TelTextRole).toString().trimmed(); linePhone = QString(" %1").arg(linePhone); QRect textRect(itemRect); textRect.adjust(0, option.fontMetrics.height(), 0, 0); drawHightlightText(painter, linePhone.isEmpty() ? "(не задан)" : linePhone, linePhone.isEmpty() ? "" : index.data(SearchTelTextRole).toString(), textRect, caseSens ? Qt::CaseSensitive : Qt::CaseInsensitive); } painter->restore(); }
Bool_t ConfigPhiMassStudy ( AliRsnMiniAnalysisTask *task, Bool_t isMC, Bool_t isPP, const char *suffix, AliRsnCutSet *cutsPair, Int_t aodFilterBit = 5, AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kFastTPCpidNsigma, Float_t nsigmaKa = 2.0, Bool_t enableTrkSyst = kFALSE, Char_t DCAxyFormula[100] = "0.0105+0.035/pt^1.01", Double_t dcazmax = 3.2, Double_t minNcls = 70, Double_t maxX2cls = 4.0, Double_t globalX2cls = 36.0, Double_t minCrossedRows = 50.0, Double_t maxClsCrossedRows = 0.8, Bool_t enableMonitor = kTRUE, Bool_t IsMcTrueOnly = kFALSE, Int_t signedPdg = 333, TString monitorOpt = "", //Flag for AddMonitorOutput.C e.g."NoSIGN" Bool_t useCrossedRows = kFALSE, const char* yaxisVar = "PtDaughter_PDaughter_cent", //yaxisVar = "PtDaughter_PDaughter_cent" Bool_t useMixLS = 0 ) { TString opt(yaxisVar); opt.ToUpper(); Bool_t isPtDaughter = opt.Contains("PTDAUGHTER") ; Bool_t isPDaughter = opt.Contains("PDAUGHTER") ; Bool_t iscent = opt.Contains("CENT") ; Bool_t iseta = opt.Contains("ETA") ; Bool_t israpidity = opt.Contains("RAPIDITY") ; // manage suffix if (strlen(suffix) > 0) suffix = Form("_%s", suffix); // set daughter cuts AliRsnCutSetDaughterParticle * cutSetQ; AliRsnCutSetDaughterParticle * cutSetK; //vary track quality cuts for systematic checks if(enableTrkSyst){ AliRsnCutTrackQuality * trkQualityCut = new AliRsnCutTrackQuality("QualityCut"); trkQualityCut->SetAODTestFilterBit(aodFilterBit);//reset the filter bit cut trkQualityCut->SetCheckOnlyFilterBit(kFALSE);//tells the cut object to check all other cuts individually, trkQualityCut->SetDCARPtFormula(DCAxyFormula); trkQualityCut->SetDCAZmax(dcazmax); if(useCrossedRows) { trkQualityCut->SetMinNCrossedRowsTPC(minCrossedRows, kTRUE); trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(maxClsCrossedRows, kTRUE); } else trkQualityCut->SetTPCminNClusters(minNcls); trkQualityCut->SetTPCmaxChi2(maxX2cls); trkQualityCut->SetITSmaxChi2(36); // In Filter bit trkQualityCut->SetMaxChi2TPCConstrainedGlobal(globalX2cls); // In the Filterbit trkQualityCut->SetPtRange(0.15, 20.0); trkQualityCut->SetEtaRange(-0.8, 0.8); trkQualityCut->Print(); if(isPP) { cutSetQ = new AliRsnCutSetDaughterParticle(Form("cutQ_bit%i",aodFilterBit), trkQualityCut, AliRsnCutSetDaughterParticle::kQualityStd2010, AliPID::kPion, -1.0); cutSetK = new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma",cutKaCandidate, nsigmaKa), trkQualityCut, cutKaCandidate, AliPID::kKaon, nsigmaKa); } else { cutSetQ = new AliRsnCutSetDaughterParticle(Form("cutQ_bit%i",aodFilterBit), trkQualityCut, AliRsnCutSetDaughterParticle::kQualityStd2011, AliPID::kPion, -1.0); cutSetK = new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma",cutKaCandidate, nsigmaKa), trkQualityCut, cutKaCandidate, AliPID::kKaon, nsigmaKa); cutSetK->SetUse2011StdQualityCuts(kTRUE); } } else { //default cuts 2010 for pp and 2011 for p-Pb if(isPP) { cutSetQ = new AliRsnCutSetDaughterParticle("cutQuality", AliRsnCutSetDaughterParticle::kQualityStd2010, AliPID::kPion, -1.0, aodFilterBit, kFALSE); cutSetK = new AliRsnCutSetDaughterParticle(Form("cutKaon_%2.1f2sigma",nsigmaKa), cutKaCandidate, AliPID::kKaon, nsigmaKa, aodFilterBit, kFALSE); } else { cutSetQ = new AliRsnCutSetDaughterParticle("cutQuality", AliRsnCutSetDaughterParticle::kQualityStd2011, AliPID::kPion, -1.0, aodFilterBit, kFALSE); cutSetQ->SetUse2011StdQualityCuts(kTRUE); cutSetK = new AliRsnCutSetDaughterParticle(Form("cutKaon2011_%2.1f2sigma",nsigmaKa), cutKaCandidate, AliPID::kKaon, nsigmaKa, aodFilterBit, kFALSE); cutSetK->SetUse2011StdQualityCuts(kTRUE); } } Int_t iCutQ = task->AddTrackCuts(cutSetQ); Int_t iCutK = task->AddTrackCuts(cutSetK); if (enableMonitor){ Printf("======== Cut monitoring enabled"); gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/AddMonitorOutput.C"); AddMonitorOutput(isMC, cutSetQ->GetMonitorOutput(), monitorOpt.Data()); AddMonitorOutput(isMC, cutSetK->GetMonitorOutput(), monitorOpt.Data()); } Int_t pdg = signedPdg; TDatabasePDG *db = TDatabasePDG::Instance(); TParticlePDG *part = db->GetParticle(pdg); Double_t mass = part->Mass(); // -- Values ------------------------------------------------------------------------------------ /* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE); /* IM resolution */ Int_t resID = task->CreateValue(AliRsnMiniValue::kInvMassRes, kTRUE); /* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE); /* centrality */ Int_t centID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE); /* pseudorapidity */ Int_t etaID = task->CreateValue(AliRsnMiniValue::kEta, kFALSE); /* rapidity */ Int_t yID = task->CreateValue(AliRsnMiniValue::kY, kFALSE); /* 1st daughter pt */ Int_t fdpt = task->CreateValue(AliRsnMiniValue::kFirstDaughterPt, kFALSE); /* 2nd daughter pt */ Int_t sdpt = task->CreateValue(AliRsnMiniValue::kSecondDaughterPt, kFALSE); /* 1st daughter p */ Int_t fdp = task->CreateValue(AliRsnMiniValue::kFirstDaughterP, kFALSE); /* 2nd daughter p */ Int_t sdp = task->CreateValue(AliRsnMiniValue::kSecondDaughterP, kFALSE); /* transv. momentum */ Int_t ptIDmc = task->CreateValue(AliRsnMiniValue::kPt, kTRUE); /* 1st daughter pt */ Int_t fdptmc = task->CreateValue(AliRsnMiniValue::kFirstDaughterPt, kTRUE); /* 2nd daughter pt */ Int_t sdptmc = task->CreateValue(AliRsnMiniValue::kSecondDaughterPt, kTRUE); // -- Create all needed outputs ----------------------------------------------------------------- // use an array for more compact writing, which are different on mixing and charges // [0] = unlike // [1] = mixing // [2] = like ++ // [3] = like -- Bool_t use [12] = { !IsMcTrueOnly, !IsMcTrueOnly, !IsMcTrueOnly,!IsMcTrueOnly,!IsMcTrueOnly,!IsMcTrueOnly, isMC , isMC , isMC , isMC , useMixLS , useMixLS}; Bool_t useIM [12] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 }; TString name [12] = {"UnlikePM" , "UnlikeMP" , "MixingPM" , "MixingMP" , "LikePP" , "LikeMM" ,"TruesPM","TruesMP","ResPM" ,"ResMP" ,"MixingPP","MixingMM"}; TString comp [12] = {"PAIR" , "PAIR" , "MIX" , "MIX" , "PAIR" , "PAIR" , "TRUE" , "TRUE" , "TRUE" , "TRUE" , "MIX" ,"MIX" }; TString output [12] = {"SPARSE" , "SPARSE" , "SPARSE" , "SPARSE" , "SPARSE" , "SPARSE" , "SPARSE","SPARSE" ,"SPARSE","SPARSE","SPARSE" ,"SPARSE"}; Char_t charge1 [12] = {'+' , '-' , '+' , '-' , '+' , '-' , '+' , '-' , '+' , '-' , '+' , '-' }; Char_t charge2 [12] = {'-' , '+' , '-' , '+' , '+' , '-' , '-' , '+' , '-' , '+' ,'+' , '-' }; Int_t cutID1 [12] = { iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK }; Int_t cutID2 [12] = { iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK , iCutK }; //TString output [10] = {"HIST" , "HIST" , "HIST" , "HIST" , "HIST" , "HIST" , "HIST" , "HIST" , "HIST" , "HIST" }; for (Int_t i = 0; i < 12; i++) { if (!use[i]) continue; AliRsnMiniOutput *out = task->CreateOutput(Form("Phi_%s%s", name[i].Data(), suffix), output[i].Data(), comp[i].Data()); out->SetCutID(0, cutID1[i]); out->SetCutID(1, cutID2[i]); out->SetDaughter(0, AliRsnDaughter::kKaon); out->SetDaughter(1, AliRsnDaughter::kKaon); out->SetCharge(0, charge1[i]); out->SetCharge(1, charge2[i]); out->SetMotherPDG(pdg); out->SetMotherMass(mass); out->SetPairCuts(cutsPair); // axis X: invmass (or resolution) if (useIM[i]) out->AddAxis(imID, 800, 0.8, 1.6); else out->AddAxis(resID, 200, -0.02, 0.02); // axis Y: transverse momentum of pair as default - else chosen value out->AddAxis(ptID, 100, 0.0, 10.0); //default use mother pt if(isPtDaughter) { out->AddAxis(fdpt, 100, 0.0, 10.0); out->AddAxis(sdpt, 100, 0.0, 10.0); } if(isPDaughter) { out->AddAxis(fdp, 100, 0.0, 10.0); out->AddAxis(sdp, 100, 0.0, 10.0); } // axis Z: centrality-multiplicity if(iscent) { if (!isPP) out->AddAxis(centID, 100, 0.0, 100.0); else out->AddAxis(centID, 400, 0.0, 400.0); } // axis W: pseudorapidity if(iseta) out->AddAxis(etaID, 20, -1.0, 1.0); // axis J: rapidity if(israpidity) out->AddAxis(yID, 12, -0.6, 0.6); } if (isMC){ // create output AliRsnMiniOutput *outm = task->CreateOutput(Form("Phi_Mother%s", suffix), "SPARSE", "MOTHER"); outm->SetDaughter(0, AliRsnDaughter::kKaon); outm->SetDaughter(1, AliRsnDaughter::kKaon); outm->SetMotherPDG(pdg); outm->SetMotherMass(mass); // pair cuts outm->SetPairCuts(cutsPair); // binnings outm->AddAxis(imID, 800, 0.8, 1.6); // axis Y: transverse momentum of pair as default - else chosen value outm->AddAxis(ptID, 100, 0.0, 10.0); //default use mother pt if(isPtDaughter) { outm->AddAxis(fdpt, 100, 0.0, 10.0); outm->AddAxis(sdpt, 100, 0.0, 10.0); } if(isPDaughter) { outm->AddAxis(fdp, 100, 0.0, 10.0); outm->AddAxis(sdp, 100, 0.0, 10.0); } if(iscent) { if (!isPP) outm->AddAxis(centID, 100, 0.0, 100.0); else outm->AddAxis(centID, 400, 0.0, 400.0); } // axis W: pseudorapidity if(iseta) outm->AddAxis(etaID, 20, -1.0, 1.0); // axis J: rapidity if(israpidity) outm->AddAxis(yID, 12, -0.6, 0.6); //create plot for generated Pt of mother vs generated Pt of daughters AliRsnMiniOutput *outPtGen = task->CreateOutput(Form("Phi_Mother_GenPt_%s", suffix), "SPARSE", "MOTHER"); outPtGen->SetDaughter(0, AliRsnDaughter::kKaon); outPtGen->SetDaughter(1, AliRsnDaughter::kKaon); outPtGen->SetMotherPDG(pdg); outPtGen->SetMotherMass(mass); // pair cuts outPtGen->SetPairCuts(cutsPair); // binnings outPtGen->AddAxis(ptIDmc, 100, 0.0, 10.0); //mother pt - generated outPtGen->AddAxis(fdptmc, 100, 0.0, 10.0); //first daughter pt - generated outPtGen->AddAxis(sdptmc, 100, 0.0, 10.0); //second daughter pt - generated //create plot for reconstructed Pt of true mother vs generated Pt of daughters AliRsnMiniOutput *outPtTrueGen = task->CreateOutput(Form("Phi_True_GenPt_%s", suffix), "SPARSE", "TRUE"); outPtTrueGen->SetDaughter(0, AliRsnDaughter::kKaon); outPtTrueGen->SetDaughter(1, AliRsnDaughter::kKaon); outPtTrueGen->SetCutID(0, iCutK); outPtTrueGen->SetCutID(1, iCutK); outPtTrueGen->SetCharge(0, '+'); outPtTrueGen->SetCharge(1, '-'); outPtTrueGen->SetMotherPDG(pdg); outPtTrueGen->SetMotherMass(mass); // pair cuts outPtTrueGen->SetPairCuts(cutsPair); // binnings outPtTrueGen->AddAxis(ptID, 100, 0.0, 10.0); //true pt - generated outPtTrueGen->AddAxis(fdptmc, 100, 0.0, 10.0); //first daughter pt - generated outPtTrueGen->AddAxis(sdptmc, 100, 0.0, 10.0); //second daughter pt - generated //create plot for reconstructed Pt of true mother vs reconstructed Pt of daughters AliRsnMiniOutput *outPtTrueRec = task->CreateOutput(Form("Phi_True_RecPt_%s", suffix), "SPARSE", "TRUE"); outPtTrueRec->SetDaughter(0, AliRsnDaughter::kKaon); outPtTrueRec->SetDaughter(1, AliRsnDaughter::kKaon); outPtTrueRec->SetCutID(0, iCutK); outPtTrueRec->SetCutID(1, iCutK); outPtTrueRec->SetCharge(0, '+'); outPtTrueRec->SetCharge(1, '-'); outPtTrueRec->SetMotherPDG(pdg); outPtTrueRec->SetMotherMass(mass); // pair cuts outPtTrueRec->SetPairCuts(cutsPair); // binnings outPtTrueRec->AddAxis(ptID, 100, 0.0, 10.0); //mother pt - reconstructed outPtTrueRec->AddAxis(fdpt, 100, 0.0, 10.0); //first daughter pt - reconstructed outPtTrueRec->AddAxis(sdpt, 100, 0.0, 10.0); //second daughter pt - reconstructed } return kTRUE; }
int main(int argc, char* argv[]) { drvq::train_args opt(argc, argv); drvq::train(opt); return 0; }
int RUNMAIN(arcinfo)(int argc, char **argv) { setlocale(LC_ALL, ""); Arc::Logger logger(Arc::Logger::getRootLogger(), "arcinfo"); Arc::LogStream logcerr(std::cerr); logcerr.setFormat(Arc::ShortFormat); Arc::Logger::getRootLogger().addDestination(logcerr); Arc::Logger::getRootLogger().setThreshold(Arc::WARNING); Arc::ArcLocation::Init(argv[0]); ClientOptions opt(ClientOptions::CO_INFO, istring("[resource ...]"), istring("The arcinfo command is used for " "obtaining the status of computing " "resources on the Grid.")); { std::list<std::string> clusterstmp = opt.Parse(argc, argv); opt.clusters.insert(opt.clusters.end(), clusterstmp.begin(), clusterstmp.end()); } if (opt.showversion) { std::cout << Arc::IString("%s version %s", "arcinfo", VERSION) << std::endl; return 0; } // If debug is specified as argument, it should be set before loading the configuration. if (!opt.debug.empty()) Arc::Logger::getRootLogger().setThreshold(Arc::string_to_level(opt.debug)); if (opt.show_plugins) { std::list<std::string> types; types.push_back("HED:ServiceEndpointRetrieverPlugin"); types.push_back("HED:TargetInformationRetrieverPlugin"); showplugins("arcinfo", types, logger); return 0; } Arc::UserConfig usercfg(opt.conffile); if (!usercfg) { logger.msg(Arc::ERROR, "Failed configuration initialization"); return 1; } if (opt.list_configured_services) { std::map<std::string, Arc::ConfigEndpoint> allServices = usercfg.GetAllConfiguredServices(); std::cout << "Configured registries:" << std::endl; for (std::map<std::string, Arc::ConfigEndpoint>::const_iterator it = allServices.begin(); it != allServices.end(); it++) { if (it->second.type == Arc::ConfigEndpoint::REGISTRY) { std::cout << " " << it->first << ": " << it->second.URLString; if (!it->second.InterfaceName.empty()) { std::cout << " (" << it->second.InterfaceName << ")"; } std::cout << std::endl; } } std::cout << "Configured computing elements:" << std::endl; for (std::map<std::string, Arc::ConfigEndpoint>::const_iterator it = allServices.begin(); it != allServices.end(); it++) { if (it->second.type == Arc::ConfigEndpoint::COMPUTINGINFO) { std::cout << " " << it->first << ": " << it->second.URLString; if (!it->second.InterfaceName.empty() || !it->second.RequestedSubmissionInterfaceName.empty()) { std::cout << " (" << it->second.InterfaceName; if (!it->second.InterfaceName.empty() && !it->second.RequestedSubmissionInterfaceName.empty()) { std::cout << " / "; } std::cout << it->second.RequestedSubmissionInterfaceName + ")"; } std::cout << std::endl; } } return 0; } if (opt.debug.empty() && !usercfg.Verbosity().empty()) Arc::Logger::getRootLogger().setThreshold(Arc::string_to_level(usercfg.Verbosity())); if (opt.timeout > 0) usercfg.Timeout(opt.timeout); std::list<Arc::Endpoint> endpoints = getServicesFromUserConfigAndCommandLine(usercfg, opt.indexurls, opt.clusters, opt.requestedSubmissionInterfaceName, opt.infointerface); std::set<std::string> preferredInterfaceNames; if (usercfg.InfoInterface().empty()) { preferredInterfaceNames.insert("org.nordugrid.ldapglue2"); } else { preferredInterfaceNames.insert(usercfg.InfoInterface()); } std::list<std::string> rejectDiscoveryURLs = getRejectDiscoveryURLsFromUserConfigAndCommandLine(usercfg, opt.rejectdiscovery); Arc::ComputingServiceUniq csu; Arc::ComputingServiceRetriever csr(usercfg, std::list<Arc::Endpoint>(), rejectDiscoveryURLs, preferredInterfaceNames); csr.addConsumer(csu); for (std::list<Arc::Endpoint>::const_iterator it = endpoints.begin(); it != endpoints.end(); ++it) { csr.addEndpoint(*it); } csr.wait(); std::list<Arc::ComputingServiceType> services = csu.getServices(); for (std::list<Arc::ComputingServiceType>::const_iterator it = services.begin(); it != services.end(); ++it) { if (opt.longlist) { if (it != services.begin()) std::cout << std::endl; std::cout << *it; std::cout << std::flush; } else { std::cout << "Computing service: " << (**it).Name; if (!(**it).QualityLevel.empty()) { std::cout << " (" << (**it).QualityLevel << ")"; } std::cout << std::endl; std::stringstream infostream, submissionstream; for (std::map<int, Arc::ComputingEndpointType>::const_iterator itCE = it->ComputingEndpoint.begin(); itCE != it->ComputingEndpoint.end(); ++itCE) { if (itCE->second->Capability.count(Arc::Endpoint::GetStringForCapability(Arc::Endpoint::COMPUTINGINFO))) { infostream << " " << Arc::IString("Information endpoint") << ": " << itCE->second->URLString << std::endl; } if (itCE->second->Capability.empty() || itCE->second->Capability.count(Arc::Endpoint::GetStringForCapability(Arc::Endpoint::JOBSUBMIT)) || itCE->second->Capability.count(Arc::Endpoint::GetStringForCapability(Arc::Endpoint::JOBCREATION))) { submissionstream << " "; submissionstream << Arc::IString("Submission endpoint") << ": "; submissionstream << itCE->second->URLString; submissionstream << " (" << Arc::IString("status") << ": "; submissionstream << itCE->second->HealthState << ", "; submissionstream << Arc::IString("interface") << ": "; submissionstream << itCE->second->InterfaceName << ")" << std::endl; } } std::cout << infostream.str() << submissionstream.str(); } } bool anEndpointFailed = false; // Check if querying endpoint succeeded. Arc::EndpointStatusMap statusMap = csr.getAllStatuses(); for (std::list<Arc::Endpoint>::const_iterator it = endpoints.begin(); it != endpoints.end(); ++it) { Arc::EndpointStatusMap::const_iterator itStatus = statusMap.find(*it); if (itStatus != statusMap.end() && itStatus->second != Arc::EndpointQueryingStatus::SUCCESSFUL && itStatus->second != Arc::EndpointQueryingStatus::SUSPENDED_NOTREQUIRED) { if (!anEndpointFailed) { anEndpointFailed = true; std::cerr << Arc::IString("ERROR: Failed to retrieve information from the following endpoints:") << std::endl; } std::cerr << " " << it->URLString; if (!itStatus->second.getDescription().empty()) { std::cerr << " (" << itStatus->second.getDescription() << ")"; } std::cerr << std::endl; } } if (anEndpointFailed) return 1; if (services.empty()) { std::cerr << Arc::IString("ERROR: Failed to retrieve information"); if (!endpoints.empty()) { std::cerr << " " << Arc::IString("from the following endpoints:") << std::endl; for (std::list<Arc::Endpoint>::const_iterator it = endpoints.begin(); it != endpoints.end(); ++it) { std::cerr << " " << it->URLString << std::endl; } } else { std::cerr << std::endl; } return 1; } return 0; }
/* Solves the optimization problem on the entire grid. */ void MomOptSolver::solveOptimization() { int numX = c_gX[3] - c_gX[0] + 1; int numY = c_gY[3] - c_gY[0] + 1; int numGridPoints = numX * numY; #pragma omp parallel for schedule(dynamic,1) for(int index = 0; index < numGridPoints; index++) { int i = index / numY; int j = index % numY; OPTIONS options; options.momentType = c_momentType; options.maxIter = c_maxIter; options.maxBfgsIter = c_maxIterBfgs; options.tolAbs = c_tolerance * c_tolerance; options.tolRel = c_tolerance; //options.tolGamma = 1.1; options.condHMax = c_condHMax; options.condHMaxBfgs = c_condHMaxBfgs; options.deltaPPn = c_deltaPPn; options.useGaunt = (c_useGaunt == 1) ? true : false; OUTS outs; switch(c_optType) { case OPT_TYPE_ORIGINAL: opt(c_numMoments, c_numManyMoments, c_numQuadPoints, &c_moments[I3D(i,j,0)], &c_alpha[I3D(i,j,0)], options, c_quadWeights, c_spHarm, &outs); break; case OPT_TYPE_CHANGE_BASIS: optcb(c_numMoments, c_numQuadPoints, &c_moments[I3D(i,j,0)], &c_P2M[I3D2(i,j,0)], &c_alphaP[I3D(i,j,0)], &c_alpha[I3D(i,j,0)], c_quadWeights, c_spHarm, options, &outs); break; case OPT_TYPE_BFGS: optbfgs(c_numMoments, c_numQuadPoints, &c_moments[I3D(i,j,0)], &c_P2M[I3D2(i,j,0)], &c_alphaP[I3D(i,j,0)], &c_alpha[I3D(i,j,0)], c_quadWeights, c_spHarm, options, &outs); break; default: printf("update.cpp: optType out of bounds.\n"); utils_abort(); } #pragma omp critical { if(outs.iter > c_optStats.maxIter) c_optStats.maxIter = outs.iter; //if(outs.iterGamma > c_optStats.maxGammaIter) // c_optStats.maxGammaIter = outs.iterGamma; for(int r = 0; r < NUM_REGULARIZATIONS; r++) { if(fabs(outs.r - REGULARIZATIONS[r]) < 1e-10) c_optStats.histReg[r]++; } c_optStats.iterMean = (c_optStats.numDualSolves * c_optStats.iterMean + outs.iter) / (c_optStats.numDualSolves + 1.0); //c_optStats.iterGammaMean = // (c_optStats.numDualSolves * c_optStats.iterGammaMean + outs.iterGamma) / // (c_optStats.numDualSolves + 1.0); c_optStats.numDualSolves++; } } }
void QAbstractScrollAreaPrivate::layoutChildren() { Q_Q(QAbstractScrollArea); bool needh = (hbarpolicy == Qt::ScrollBarAlwaysOn || (hbarpolicy == Qt::ScrollBarAsNeeded && hbar->minimum() < hbar->maximum())); bool needv = (vbarpolicy == Qt::ScrollBarAlwaysOn || (vbarpolicy == Qt::ScrollBarAsNeeded && vbar->minimum() < vbar->maximum())); #ifdef Q_WS_MAC QWidget * const window = q->window(); // Use small scroll bars for tool windows, to match the native size grip. bool hbarIsSmall = hbar->testAttribute(Qt::WA_MacSmallSize); bool vbarIsSmall = vbar->testAttribute(Qt::WA_MacSmallSize); const Qt::WindowType windowType = window->windowType(); if (windowType == Qt::Tool) { if (!hbarIsSmall) { hbar->setAttribute(Qt::WA_MacMiniSize, false); hbar->setAttribute(Qt::WA_MacNormalSize, false); hbar->setAttribute(Qt::WA_MacSmallSize, true); } if (!vbarIsSmall) { vbar->setAttribute(Qt::WA_MacMiniSize, false); vbar->setAttribute(Qt::WA_MacNormalSize, false); vbar->setAttribute(Qt::WA_MacSmallSize, true); } } else { if (hbarIsSmall) { hbar->setAttribute(Qt::WA_MacMiniSize, false); hbar->setAttribute(Qt::WA_MacNormalSize, false); hbar->setAttribute(Qt::WA_MacSmallSize, false); } if (vbarIsSmall) { vbar->setAttribute(Qt::WA_MacMiniSize, false); vbar->setAttribute(Qt::WA_MacNormalSize, false); vbar->setAttribute(Qt::WA_MacSmallSize, false); } } #endif const int hsbExt = hbar->sizeHint().height(); const int vsbExt = vbar->sizeHint().width(); const QPoint extPoint(vsbExt, hsbExt); const QSize extSize(vsbExt, hsbExt); const QRect widgetRect = q->rect(); QStyleOption opt(0); opt.init(q); const bool hasCornerWidget = (cornerWidget != 0); // If the scroll bars are at the very right and bottom of the window we // move their positions to be aligned with the size grip. #ifdef Q_WS_MAC // Check if a native sizegrip is present. bool hasMacReverseSizeGrip = false; bool hasMacSizeGrip = false; bool nativeGripPresent = false; if (q->testAttribute(Qt::WA_WState_Created)) nativeGripPresent = qt_mac_checkForNativeSizeGrip(q); if (nativeGripPresent) { // Look for a native size grip at the visual window bottom right and at the // absolute window bottom right. In reverse mode, the native size grip does not // swich side, so we need to check if it is on the "wrong side". const QPoint scrollAreaBottomRight = q->mapTo(window, widgetRect.bottomRight() - QPoint(frameWidth, frameWidth)); const QPoint windowBottomRight = window->rect().bottomRight(); const QPoint visualWindowBottomRight = QStyle::visualPos(opt.direction, opt.rect, windowBottomRight); const QPoint offset = windowBottomRight - scrollAreaBottomRight; const QPoint visualOffset = visualWindowBottomRight - scrollAreaBottomRight; hasMacSizeGrip = (visualOffset.manhattanLength() < vsbExt); hasMacReverseSizeGrip = (hasMacSizeGrip == false && (offset.manhattanLength() < hsbExt)); } #endif QPoint cornerOffset(needv ? vsbExt : 0, needh ? hsbExt : 0); QRect controlsRect; QRect viewportRect; // In FrameOnlyAroundContents mode the frame is drawn between the controls and // the viewport, else the frame rect is equal to the widget rect. if ((frameStyle != QFrame::NoFrame) && q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &opt, q)) { controlsRect = widgetRect; const int extra = q->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &opt, q); const QPoint cornerExtra(needv ? extra : 0, needh ? extra : 0); QRect frameRect = widgetRect; frameRect.adjust(0, 0, -cornerOffset.x() - cornerExtra.x(), -cornerOffset.y() - cornerExtra.y()); q->setFrameRect(QStyle::visualRect(opt.direction, opt.rect, frameRect)); // The frame rect needs to be in logical coords, however we need to flip // the contentsRect back before passing it on to the viewportRect // since the viewportRect has its logical coords calculated later. viewportRect = QStyle::visualRect(opt.direction, opt.rect, q->contentsRect()); } else { q->setFrameRect(QStyle::visualRect(opt.direction, opt.rect, widgetRect)); controlsRect = q->contentsRect(); viewportRect = QRect(controlsRect.topLeft(), controlsRect.bottomRight() - cornerOffset); } // If we have a corner widget and are only showing one scroll bar, we need to move it // to make room for the corner widget. if (hasCornerWidget && (needv || needh)) cornerOffset = extPoint; #ifdef Q_WS_MAC // Also move the scroll bars if they are covered by the native Mac size grip. if (hasMacSizeGrip) cornerOffset = extPoint; #endif // The corner point is where the scroll bar rects, the corner widget rect and the // viewport rect meets. const QPoint cornerPoint(controlsRect.bottomRight() + QPoint(1, 1) - cornerOffset); // Some styles paints the corner if both scorllbars are showing and there is // no corner widget. Also, on the Mac we paint if there is a native // (transparent) sizegrip in the area where a corner widget would be. if ((needv && needh && hasCornerWidget == false) || ((needv || needh) #ifdef Q_WS_MAC && hasMacSizeGrip #endif ) ) { cornerPaintingRect = QStyle::visualRect(opt.direction, opt.rect, QRect(cornerPoint, extSize)); } else { cornerPaintingRect = QRect(); } #ifdef Q_WS_MAC if (hasMacReverseSizeGrip) reverseCornerPaintingRect = QRect(controlsRect.bottomRight() + QPoint(1, 1) - extPoint, extSize); else reverseCornerPaintingRect = QRect(); #endif if (needh) { QRect horizontalScrollBarRect(QPoint(controlsRect.left(), cornerPoint.y()), QPoint(cornerPoint.x() - 1, controlsRect.bottom())); #ifdef Q_WS_MAC if (hasMacReverseSizeGrip) horizontalScrollBarRect.adjust(vsbExt, 0, 0, 0); #endif scrollBarContainers[Qt::Horizontal]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, horizontalScrollBarRect)); scrollBarContainers[Qt::Horizontal]->raise(); } if (needv) { const QRect verticalScrollBarRect (QPoint(cornerPoint.x(), controlsRect.top()), QPoint(controlsRect.right(), cornerPoint.y() - 1)); scrollBarContainers[Qt::Vertical]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, verticalScrollBarRect)); scrollBarContainers[Qt::Vertical]->raise(); } if (cornerWidget) { const QRect cornerWidgetRect(cornerPoint, controlsRect.bottomRight()); cornerWidget->setGeometry(QStyle::visualRect(opt.direction, opt.rect, cornerWidgetRect)); } scrollBarContainers[Qt::Horizontal]->setVisible(needh); scrollBarContainers[Qt::Vertical]->setVisible(needv); if (q->isRightToLeft()) viewportRect.adjust(right, top, -left, -bottom); else viewportRect.adjust(left, top, -right, -bottom); viewport->setGeometry(QStyle::visualRect(opt.direction, opt.rect, viewportRect)); // resize the viewport last }
int main(int nargs, char *args[]) { int n = 6; // Number of dimensions // Common configuration // See parameters.h for the available options // If we initialize the struct with the DEFAUL_PARAMS, // the we can optionally change only few of them bopt_params par = initialize_parameters_to_default(); par.kernel.hp_mean[0] = KERNEL_THETA; par.kernel.hp_std[0] = 1.0; par.kernel.n_hp = 1; par.mean.coef_mean[0] = 0.0; par.mean.coef_std[0] = MEAN_SIGMA; par.mean.n_coef = 1; par.noise = DEFAULT_NOISE; par.surr_name = "sStudentTProcessJef"; par.n_iterations = 20; // Number of iterations par.n_init_samples = 20; /*******************************************/ size_t nPoints = 1000; randEngine mtRandom; matrixd xPoints(nPoints,n); vecOfvec xP; //Thanks to the quirks of Visual Studio, the following expression is invalid, //so we have to replace it by a literal. //WARNING: Make sure to update the size of the array if the number of points //or dimensions change. #ifdef _MSC_VER double xPointsArray[6000]; #else const size_t nPinArr = n*nPoints; double xPointsArray[nPinArr]; #endif bayesopt::utils::lhs(xPoints,mtRandom); for(size_t i = 0; i<nPoints; ++i) { vectord point = row(xPoints,i); xP.push_back(point); for(size_t j=0; j<n; ++j) { xPointsArray[i*n+j] = point(j); } } // Run C++ interface std::cout << "Running C++ interface" << std::endl; ExampleDisc opt(xP,par); vectord result(n); opt.optimize(result); // Run C interface std::cout << "Running C interface" << std::endl; double x[128], fmin[128]; bayes_optimization_disc(n, &testFunction, NULL, xPointsArray, nPoints, x, fmin, par); // Find the optimal value size_t min = 0; double minvalue = opt.evaluateSample(row(xPoints,min)); for(size_t i = 1; i<nPoints; ++i) { vectord point = row(xPoints,i); if (opt.evaluateSample(point) < minvalue) { min = i; minvalue = opt.evaluateSample(row(xPoints,min)); std::cout << i << "," << minvalue << std::endl; } } std::cout << "Final result C++: " << result << std::endl; std::cout << "Final result C: ("; for (int i = 0; i < n; i++ ) std::cout << x[i] << ", "; std::cout << ")" << std::endl; std::cout << "Optimal: " << row(xPoints,min) << std::endl; }
int main(int argc, char** argv) { String pegasusHome; Boolean shutdownOption = false; Boolean debugOutputOption = false; // Set Message loading to process locale MessageLoader::_useProcessLocale = true; #ifdef PEGASUS_OS_ZOS // Direct standard input to /dev/null, close(STDIN_FILENO); open("/dev/null", O_RDONLY); if ( setEBCDICEncoding(STDOUT_FILENO)==-1 || setEBCDICEncoding(STDERR_FILENO)==-1 ) { PEG_TRACE_CSTRING(TRC_SERVER,Tracer::LEVEL1, "Coud not set stdout or stderr to EBCDIC encoding."); } // Need to initialize timezone information in the // initial processing thread (IPT) initialize_zOS_timezone(); #endif #if defined(PEGASUS_OS_AIX) && defined(PEGASUS_HAS_MESSAGES) setlocale(LC_ALL, ""); #endif #ifndef PEGASUS_OS_TYPE_WINDOWS // // Get environment variables: // # if defined(PEGASUS_OS_AIX) && defined(PEGASUS_USE_RELEASE_DIRS) pegasusHome = AIX_RELEASE_PEGASUS_HOME; # elif defined(PEGASUS_OS_PASE) const char *tmp = getenv("PEGASUS_HOME"); pegasusHome = (tmp == 0) ? PASE_DEFAULT_PEGASUS_HOME : tmp; # elif !defined(PEGASUS_USE_RELEASE_DIRS) || \ defined(PEGASUS_OS_ZOS) const char* tmp = getenv("PEGASUS_HOME"); if (tmp) { pegasusHome = tmp; } # endif FileSystem::translateSlashes(pegasusHome); #else // windows only //setHome(pegasusHome); pegasusHome = _cimServerProcess->getHome(); #endif #ifdef PEGASUS_ENABLE_PRIVILEGE_SEPARATION // If invoked with "--executor-socket <socket>" option, then use executor. Executor::setSock(_extractExecutorSockOpt(argc, argv)); // Ping executor to verify the specified socket is valid. if (Executor::ping() != 0) { MessageLoaderParms parms("src.Server.cimserver.EXECUTOR_PING_FAILED", "Failed to ping the executor on the specified socket."); cerr << argv[0] << ": " << MessageLoader::getMessage(parms) << endl; exit(1); } #endif /* !defined(PEGASUS_ENABLE_PRIVILEGE_SEPARATION) */ // Get help, version, status and shutdown options for (int i = 1; i < argc; ) { const char* arg = argv[i]; if (strcmp(arg, "--help") == 0) { PrintHelp(argv[0]); Executor::daemonizeExecutor(); exit(0); } if (strcmp(arg, "--status") == 0) { int retValue = 0; if (_serverRunStatus.isServerRunning()) { MessageLoaderParms parms( "src.Server.cimserver.CIMSERVER_RUNNING", "The CIM Server is running."); cout << MessageLoader::getMessage(parms) << endl; } else { MessageLoaderParms parms( "src.Server.cimserver.CIMSERVER_NOT_RUNNING", "The CIM Server is not running."); cout << MessageLoader::getMessage(parms) << endl; retValue = 2; } Executor::daemonizeExecutor(); exit(retValue); } else if (strcmp(arg, "--version") == 0) { cout << _cimServerProcess->getCompleteVersion() << endl; Executor::daemonizeExecutor(); exit(0); } // Check for -option else if (*arg == '-') { // Get the option const char* option = arg + 1; // // Check to see if user asked for the version (-v option): // if (*option == OPTION_VERSION && strlen(option) == 1) { cout << _cimServerProcess->getCompleteVersion() << endl; Executor::daemonizeExecutor(); exit(0); } // // Check to see if user asked for help (-h option): // else if (*option == OPTION_HELP && (strlen(option) == 1)) { PrintHelp(argv[0]); Executor::daemonizeExecutor(); exit(0); } #if !defined(PEGASUS_USE_RELEASE_DIRS) else if (*option == OPTION_HOME && (strlen(option) == 1)) { if (i + 1 < argc) { pegasusHome.assign(argv[i + 1]); } else { String opt(option); MessageLoaderParms parms( "src.Server.cimserver.MISSING_ARGUMENT", "Missing argument for option -$0", opt); cout << MessageLoader::getMessage(parms) << endl; exit(1); } memmove(&argv[i], &argv[i + 2], (argc-i-1) * sizeof(char*)); argc -= 2; } #endif // // Check to see if user asked for debug output (-X option): // else if (*option == OPTION_DEBUGOUTPUT && (strlen(option) == 1)) { MessageLoaderParms parms( "src.Server.cimserver.UNSUPPORTED_DEBUG_OPTION", "Unsupported debug output option is enabled."); cout << MessageLoader::getMessage(parms) << endl; debugOutputOption = true; #if defined(PEGASUS_OS_HPUX) System::bindVerbose = true; #endif // remove the option from the command line memmove(&argv[i], &argv[i + 1], (argc-i) * sizeof(char*)); argc--; } // // Check to see if user asked for shutdown (-s option): // else if (*option == OPTION_SHUTDOWN && (strlen(option) == 1)) { // // Check to see if shutdown has already been specified: // if (shutdownOption) { MessageLoaderParms parms( "src.Server.cimserver.DUPLICATE_SHUTDOWN_OPTION", "Duplicate shutdown option specified."); cout << MessageLoader::getMessage(parms) << endl; exit(1); } shutdownOption = true; // remove the option from the command line memmove(&argv[i], &argv[i + 1], (argc-i) * sizeof(char*)); argc--; } else i++; } else i++; } // // Set the value for pegasusHome property // ConfigManager::setPegasusHome(pegasusHome); // // Do the platform specific run // return _cimServerProcess->platform_run( argc, argv, shutdownOption, debugOutputOption); }
int main(int argc, char* argv[]) { drvq::flat_args opt(argc, argv); drvq::flatten(opt); return 0; }
QPixmap QtopiaSvgIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) { QString key = createKey(d->filename, size, mode, state); QPixmap pm; // Try explicitly added pixmaps first if (d->pixmaps) { if (d->pixmaps->contains(key)) return d->pixmaps->value(key); } // See if we have it in our local cache first. if (QPixmapCache::find(key, pm)) return pm; // Perhaps it has already been stored in the global cache. bool globalCandidate = false; if (size.height() == QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize) || size.height() == QApplication::style()->pixelMetric(QStyle::PM_TabBarIconSize) || size.height() == QApplication::style()->pixelMetric(QStyle::PM_LargeIconSize) || size.height() == QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize)) { if (QGlobalPixmapCache::find(key, pm)) { qLog(Resource) << "Icon found in global cache" << d->filename; return pm; } globalCandidate = true; qLog(Resource) << "Icon not found in global cache" << d->filename; } if (!d->loaded) { if (!d->render) d->render = new QSvgRenderer; d->render->load(d->filename); qLog(Resource) << "loaded svg icon" << d->filename; d->loaded = true; } QImage img(size, QImage::Format_ARGB32_Premultiplied); img.fill(0x00000000); QPainter p(&img); d->render->render(&p); p.end(); pm = QPixmap::fromImage(img); QStyleOption opt(0); opt.palette = QApplication::palette(); QPixmap generated = QApplication::style()->generatedIconPixmap(mode, pm, &opt); if (!generated.isNull()) pm = generated; // We'll only put the standard icon sizes in the cache because // there's a high likelyhood that they'll be used by others. if (globalCandidate) { if (QGlobalPixmapCache::insert(key, pm)) return pm; } // Still worthwhile putting in the local cache since it is very likely // to be rendered again QPixmapCache::insert(key, pm); return pm; }
int main(int argc, char* argv[]) { TlGetopt opt(argc, argv, "d:f:mrs"); std::size_t count = 10 * 1024 * 1024; int dim = 1000; if (!opt["d"].empty()) { dim = std::atoi(opt["d"].c_str()); } std::string mmap_file = "/tmp/mmap_bench.map"; if (!opt["f"].empty()) { mmap_file = opt["f"]; } bool isSymmetric = false; if (!opt["s"].empty()) { isSymmetric = true; } bool isMMap = false; if (!opt["m"].empty()) { isMMap = true; } bool isRandom = false; if (!opt["r"].empty()) { isRandom = true; } // show information std::cout << TlUtils::format("(%6d, %6d) ", dim, dim); if (isSymmetric == true) { std::cout << TlUtils::format( "[sym] mem_size=%8.2fMB ", double(dim * (dim + 1) * sizeof(double)) / (2.0 * 1024.0 * 1024.0)); } else { std::cout << TlUtils::format( "[---] mem_size=%8.2fMB ", double(dim * dim * sizeof(double)) / (1024.0 * 1024.0)); } if (isMMap == true) { std::cout << "[mmap ] "; } else { std::cout << "[memory] "; } if (isRandom == true) { std::cout << "[random R/W ] " << std::endl; } else { std::cout << "[sequential R/W] " << std::endl; } // bench double elapse = 0.0; if (isMMap == true) { std::size_t needMemSize = dim * dim * sizeof(double) + 100; // 100は念のため TlMemManager::setParam(needMemSize, mmap_file); TlMatrix::useMemManager(true); } if (isSymmetric == true) { TlDenseSymmetricMatrix_BLAS_Old m(dim); if (isRandom == true) { elapse = bench_rand(count, &m); } else { elapse = bench_seq(count, &m); } } else { TlMatrix m(dim, dim); if (isRandom == true) { elapse = bench_rand(count, &m); } else { elapse = bench_seq(count, &m); } } // results std::cout << "access time = " << elapse << " [s]" << std::endl; std::size_t dataSize = count * sizeof(double) * 2; // *2 = get, set double ratio = dataSize / elapse; std::cout << "ratio = " << (ratio / (1024.0 * 1024.0)) << " MB/sec" << std::endl; return EXIT_SUCCESS; }
int main(int argc,char **argv) { log4cxx::PropertyConfigurator::configure("../comm/log4cxx.properties"); //插入非数值型数据 std::string dbname1 = "test"; std::string collection_name1 = "kelp"; try{ kelp::MongoOperator opt(dbname1,collection_name1); std::string key = "handsome"; std::string value = "Chenjian"; opt.Insert(key,value);//非数值型数据 value = "ChenChen"; mongo::BSONObj key_value =BSON(key<<value); opt.Insert(key_value); //插入bool型数据 bool bool_value = "true"; for(int i = 0;i < 10; i++) opt.Insert(key,bool_value); //查询非数值型数据,测试键值对查询方式 mongo::BSONObj query_condition = BSON(key<<value); std::vector<mongo::BSONObj>query_outcome; opt.QueryData(query_condition,query_outcome); for(std::vector<mongo::BSONObj> ::iterator it =query_outcome.begin();it!=query_outcome.end();++it) std::cout << (*it).toString() << std::endl; } catch(std::runtime_error &r) { std::cout << r.what() << std::endl; return -1; } //插入数值型数据,测试非键值对插入方式 std::string dbname2 = "test"; std::string collection_name2 = "xuxijian"; try{ kelp::MongoOperator opt2(dbname2,collection_name2); std::string double_key = "id"; int value_size = 5; double double_value[5] = {10086.12345,12.332,76.12,521.123,67.2234}; for(int i = 0;i < value_size;i++) opt2.Insert(double_key,double_value[i]); //查询数值数据 std::vector<mongo::BSONObj>query_outcome_2; mongo::BSONObj query_condition = BSON(double_key<<double_value[0]); opt2.QueryData(query_condition,query_outcome_2); for(std::vector<mongo::BSONObj> ::iterator it =query_outcome_2.begin();it!=query_outcome_2.end();++it) std::cout << (*it).toString() << std::endl; //插入图片 //const std::string filename = "~/Kelp/src/comm/test.jpg"; //opt2.Insert(filename); } catch(std::runtime_error &r) { std::cout << r.what() <<std::endl; return -1; } return 0; }
int main(int argc, char** argv) { int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); rokko::grid_1d g; if (g.get_nprocs() > 1) { std::cerr << "currently works only for Np = 1\n"; } std::cout.precision(10); options opt(argc, argv, 16, solver_type::default_solver(), g.get_myrank() == 0); if (!opt.valid) MPI_Abort(MPI_COMM_WORLD, 1); boost::timer tm; MPI_Barrier(g.get_comm()); double t1 = tm.elapsed(); // lattice structure int n = opt.N; int ibond = n; std::vector<int> ipair; for (int i = 0; i < ibond; ++i) { ipair.push_back(i); ipair.push_back((i + 1) % n); } // Hamiltonian parameters std::vector<double> bondwt(ibond, -1); std::vector<double> zrtio(ibond, 1); // table of configurations and Hamiltonian operator subspace ss(n, 0); hamiltonian hop(ss, ipair, bondwt, zrtio); solver_type solver(opt.solver); solver.initialize(argc, argv); MPI_Barrier(g.get_comm()); double t2 = tm.elapsed(); // Eigenvalues int nev = 10; int blockSize = 5; int maxIters = 500; double tol = 1.0e-8; solver.diagonalize(hop, nev, blockSize, maxIters, tol); double t3 = tm.elapsed(); if (g.get_myrank() == 0) { std::cout << "[Number of converged eigenpairs]\n\t" << solver.num_conv() << std::endl; // std::cout << "[Iteration number]\n\t" << itr << std::endl; std::cout << "[Eigenvalues]\n"; for (int i = 0; i < solver.num_conv(); ++i) std::cout << '\t' << solver.eigenvalue(i); std::cout << std::endl; } // Ground-state eigenvector rokko::distributed_vector eigvec; solver.eigenvector(0, eigvec); if (g.get_myrank() == 0) std::cout << "[Eigenvector components (selected)]"; std::cout << std::flush; MPI_Barrier(g.get_comm()); int count = 0; for (int i = 12; i < ss.dimension(); i += ss.dimension()/20, ++count) { if (eigvec.is_gindex(i)) { if (count % 4 == 0) std::cout << std::endl; std::cout << '\t' << eigvec.get_global(i); } std::cout << std::flush; MPI_Barrier(g.get_comm()); } if (g.get_myrank() == 0) std::cout << std::endl; std::cout << std::flush; MPI_Barrier(g.get_comm()); // Precision check and correlation functions // double Hexpec = check2(mat, x, 0, v, 0); // std::vector<int> npair; // npair.push_back(1); // npair.push_back(2); // std::vector<double> sxx(1), szz(1); // xcorr(ss, npair, x, 0, sxx); // zcorr(ss, npair, x, 0, szz); // std::cout << "[Nearest neighbor correlation functions]\n\t" // << "sxx : " << sxx[0] // << ", szz : " << szz[0] << std::endl; if (g.get_myrank() == 0) { std::cerr << "initialize " << (t2-t1) << " sec\n" << "diagonalization " << (t3-t2) << " sec\n"; // << "check " << (t4-t3) << " sec\n" // << "correlation " << (t5-t4) << " sec\n"; } MPI_Finalize(); }
int main( int argc, char ** argv ) { // Register custom message handler if desired bool handler_registered = FALSE; MyMessageOutput * mymsghandler = NULL; for(int i = 1; i < argc; i++) { QString arg(argv[i]); QString opt("-msg_handler"); if(arg.startsWith(opt)) { // Extract handler type QString handler = arg.section("=",1,1); if(handler.isEmpty()) { qWarning("Option '-msg_handler' is not complete. Use default handler."); handler_registered = TRUE; break; } if(handler == "console") { handler_registered = TRUE; break; } if(!handler.endsWith(".txt")) { qWarning("File '%s' does not end with '.txt'. Use default handler.",handler.ascii()); handler_registered = TRUE; break; } QFileInfo hfinfo(handler); if(hfinfo.exists()) { if(!hfinfo.isWritable()) { qWarning("Cannot write to '%s'. Use default handler",handler.ascii()); handler_registered = TRUE; break; } } else { QString path = hfinfo.dirPath(); QFileInfo hfdinfo(path); if(!hfdinfo.isWritable()) { qWarning("Cannot create file in dir '%s'. Use default handler",path.ascii()); handler_registered = TRUE; break; } } mymsghandler = new MyMessageOutput(handler); handler_registered = TRUE; break; } } if(!handler_registered) { mymsghandler = new MyMessageOutput(QString("debuglog.txt")); handler_registered = TRUE; } #ifdef Q_WS_X11 if(XInitThreads() == 0) qFatal("XInitThreads didn't succeed"); #endif // Create a QApplication object and add default close QApplication a( argc, argv ); a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) ); // Start the configuration selection dialog if more than one config file is available ConfigSelector cs; if(cs.getNumConfigs() > 1) { cs.resize(300,150); cs.show(); a.exec(); } // Load configuration Configuration * config = new Configuration(); QString configfile(cs.getConfig()); if(!config->load(configfile)) { qFatal("Unable to load %s", configfile.ascii()); } ConfigNode * cn = config->getConfig(); if(!cn) { qFatal("Unable to get ConfigNode"); } ApplicationNode * an = cn->getApplicationNode(); if(!an) { qFatal("Unable to get ApplicationNode"); } PluginsNode * pn = cn->getPluginsNode(); if(!pn) { qFatal("Unable to get PluginsNode"); } OBJECTVALUENODE_DECLARE_AND_GET(QPoint,position,an); OBJECTVALUENODE_DECLARE_AND_GET(QSize,size,an); SIMPLEVALUENODE_DECLARE_AND_GET(bool,maximized,an); SIMPLEVALUENODE_DECLARE_AND_GET(Q_INT8,tbindex,an); // Create the toplevel window Q3HBox * w = new Q3HBox(); w->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); // Add a widget that contains the toolbox and measurements Q3VBox * pVBox = new Q3VBox( w ); pVBox->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Preferred ); pVBox->setSpacing( 5 ); pVBox->setMargin( 2 ); // Create the toolbox QToolBox * tb = new QToolBox( pVBox ); // Create all plugins Plugin * VisualizePlugin = new Plugin("visualize"); Plugin * AnalysePlugin = new Plugin("analyse_os"); Plugin * WaveInPlugin = new Plugin("wavein"); Plugin * FileWriterPlugin = new Plugin("filewriter"); // Load plugin objects PI_Unknown *ukvi = VisualizePlugin->getObject(); PI_Unknown *ukan = AnalysePlugin->getObject(); PI_Unknown *ukwi = WaveInPlugin->getObject(); PI_Unknown *ukfw = FileWriterPlugin->getObject(); // Configure the system if( ukvi && ukan && ukwi && ukfw ) { PI_GuiContainer* gcwiobj = NULL; PI_GuiContainer* gcviobj = NULL; PI_GuiContainer* gcfwobj = NULL; PI_Configuration* xcanobj = NULL; PI_Configuration* xcviobj = NULL; PI_Configuration* xcwiobj = NULL; PI_Configuration* xcfwobj = NULL; PI_DataBufferProvider* dbpwiobj = NULL; PI_DataBufferProvider* dbpanobj = NULL; PI_DataBufferConsumer* dbcanobj = NULL; PI_DataBufferConsumer* dbcviobj = NULL; PI_DataBufferConsumer* dbcfwobj = NULL; PI_TimeProvider* tpwiobj = NULL; PI_TimeConsumer* tcviobj = NULL; PI_TimeConsumer* tcfwobj = NULL; ukwi->queryInterface( PIID_GUI_CONTAINER, (void**)&gcwiobj ); ukvi->queryInterface( PIID_GUI_CONTAINER , (void**)&gcviobj ); ukfw->queryInterface( PIID_GUI_CONTAINER, (void**)&gcfwobj ); ukan->queryInterface( PIID_CONFIGURATION, (void**)&xcanobj ); ukvi->queryInterface( PIID_CONFIGURATION, (void**)&xcviobj ); ukwi->queryInterface( PIID_CONFIGURATION, (void**)&xcwiobj ); ukfw->queryInterface( PIID_CONFIGURATION, (void**)&xcfwobj ); ukwi->queryInterface( PIID_DATA_BUFFER_PROVIDER, (void**)&dbpwiobj ); ukan->queryInterface( PIID_DATA_BUFFER_PROVIDER, (void**)&dbpanobj ); ukan->queryInterface( PIID_DATA_BUFFER_CONSUMER, (void**)&dbcanobj ); ukvi->queryInterface( PIID_DATA_BUFFER_CONSUMER, (void**)&dbcviobj ); ukfw->queryInterface( PIID_DATA_BUFFER_CONSUMER, (void**)&dbcfwobj ); ukwi->queryInterface( PIID_TIME_PROVIDER, (void**)&tpwiobj ); ukvi->queryInterface( PIID_TIME_CONSUMER, (void**)&tcviobj ); ukfw->queryInterface( PIID_TIME_CONSUMER, (void**)&tcfwobj ); if( gcwiobj && gcviobj && gcfwobj && xcwiobj && xcanobj && xcviobj && xcfwobj && dbpwiobj && dbpanobj && dbcanobj && dbcviobj && dbcfwobj && tpwiobj && tcviobj && tcfwobj) { // Wave in object gcwiobj->setParentWindow( tb, "WaveDeviceConfiguration" ); // Visualize object gcviobj->setParentWindow( tb, "Diagram1" ); gcviobj->setParentWindow( tb, "Diagram2" ); gcviobj->setParentWindow( tb, "Diagram3" ); gcviobj->setParentWindow( tb, "Diagram4" ); gcviobj->setParentWindow( tb, "Diagram5" ); gcviobj->setParentWindow( tb, "Configuration" ); gcviobj->setParentWindow( tb, "BaseFrequency" ); gcviobj->setParentWindow( pVBox, "TopDisplay" ); gcviobj->setParentWindow( w, "Graph" ); // File writer object gcfwobj->setParentWindow( tb, "SpectralDataSaveGui" ); // Wave in object PLUGINNODE_DECLARE_AND_GET(wavein,pn); xcwiobj->configure(NODE_VARIABLE_NAME(wavein)); // Analyse object PLUGINNODE_DECLARE_AND_GET(analyse,pn); xcanobj->configure(NODE_VARIABLE_NAME(analyse)); // Visualize object PLUGINNODE_DECLARE_AND_GET(visualize,pn); xcviobj->configure(NODE_VARIABLE_NAME(visualize)); // File writer object PLUGINNODE_DECLARE_AND_GET(filewriter,pn); xcfwobj->configure(NODE_VARIABLE_NAME(filewriter)); // Connect the 'pause' source to different sinks gcviobj->connectSlot( "pause", gcwiobj->getObject("WaveDeviceConfiguration"), "setPause" ); gcviobj->connectSlot( "pause", gcfwobj->getObject("SpectralDataSaveGui"), "setPause" ); // Add visualize object configurations to the toolbox tb->addItem( gcviobj->getWidget("Diagram1"), "Diagramm 1" ); tb->addItem( gcviobj->getWidget("Diagram2"), "Diagramm 2" ); tb->addItem( gcviobj->getWidget("Diagram3"), "Diagramm 3" ); tb->addItem( gcviobj->getWidget("Diagram4"), "Diagramm 4" ); tb->addItem( gcviobj->getWidget("Diagram5"), "Diagramm 5" ); tb->addItem( gcviobj->getWidget("Configuration"), "Konfiguration" ); tb->addItem( gcviobj->getWidget("BaseFrequency"), "Bezugston, Stimmung" ); // Add file writer object configuration to the toolbox tb->addItem( gcfwobj->getWidget("SpectralDataSaveGui"), "Datenspeicherung" ); // Add wave in object configuration to the toolbox tb->addItem( gcwiobj->getWidget("WaveDeviceConfiguration"), "Soundkarte" ); dbpwiobj->addRef(); dbcanobj->connectToProvider( dbpwiobj ); dbpanobj->addRef(); dbcviobj->connectToProvider( dbpanobj ); dbpwiobj->addRef(); dbcfwobj->connectToProvider( dbpwiobj ); //filewrite dbpanobj->addRef(); dbcfwobj->connectToProvider( dbpanobj ); //filewrite tpwiobj->addRef(); tcviobj->connectToProvider( tpwiobj ); tpwiobj->addRef(); tcfwobj->connectToProvider( tpwiobj ); //filewrite xcwiobj->startRunning(); xcanobj->startRunning(); xcviobj->startRunning(); xcfwobj->startRunning(); //filewrite } if( gcwiobj ) gcwiobj->release(); if( gcviobj ) gcviobj->release(); if( gcfwobj ) gcfwobj->release(); if( xcanobj ) xcanobj->release(); if( xcviobj ) xcviobj->release(); if( xcwiobj ) xcwiobj->release(); if( xcfwobj ) xcfwobj->release(); if( dbpwiobj ) dbpwiobj->release(); if( dbpanobj ) dbpanobj->release(); if( dbcanobj ) dbcanobj->release(); if( dbcviobj ) dbcviobj->release(); if( dbcfwobj ) dbcfwobj->release(); if( tpwiobj ) tpwiobj->release(); if( tcviobj ) tcviobj->release(); if( tcfwobj ) tcfwobj->release(); } // Set active item in the ToolBox tb->setCurrentIndex(VALUENODE_GET_VALUE(tbindex)); w->resize(VALUENODE_GET_VALUE(size)); w->move(VALUENODE_GET_VALUE(position)); if(VALUENODE_GET_VALUE(maximized)) w->showMaximized(); w->setCaption("Prisma-Realtime v1.3b"); w->show(); Q3Accel *esc = new Q3Accel( w ); esc->connectItem( esc->insertItem( Qt::Key_Escape ), &a, SLOT( quit() ) ); a.exec(); w->hide(); if(!w->isMaximized()) { VALUENODE_SET_VALUE(size,w->size()); VALUENODE_SET_VALUE(position,w->pos()); } VALUENODE_SET_VALUE(maximized,w->isMaximized()); VALUENODE_SET_VALUE(tbindex,tb->currentIndex()); if( ukvi && ukan && ukwi && ukfw ) { PI_Configuration * xmlconfig = NULL; ukvi->queryInterface(PIID_CONFIGURATION, (void**)&xmlconfig); if(xmlconfig != NULL) { xmlconfig->stopRunning(); xmlconfig->release(); xmlconfig = NULL; } ukan->queryInterface(PIID_CONFIGURATION, (void**)&xmlconfig); if(xmlconfig != NULL) { xmlconfig->stopRunning(); xmlconfig->release(); xmlconfig = NULL; } ukwi->queryInterface(PIID_CONFIGURATION, (void**)&xmlconfig); if(xmlconfig != NULL) { xmlconfig->stopRunning(); xmlconfig->release(); xmlconfig = NULL; } ukfw->queryInterface(PIID_CONFIGURATION, (void**)&xmlconfig); if(xmlconfig != NULL) { xmlconfig->stopRunning(); xmlconfig->release(); xmlconfig = NULL; } } if(ukvi) ukvi->release(); if(ukan) ukan->release(); if(ukwi) ukwi->release(); if(ukfw) ukfw->release(); delete w; config->save(configfile); // Delete before unloading plugins!!! delete config; // Release plugins delete VisualizePlugin; delete FileWriterPlugin; delete AnalysePlugin; delete WaveInPlugin; if(mymsghandler) delete mymsghandler; return 0; }