void query(DATATYPE *quy, unsigned size, DATATYPE *indices, DATATYPE *dists, unsigned type, unsigned K) { Matrix<DATATYPE>::Accessor accessor(data); Metric<DATATYPE> metric(data.getDim(), type); Scanner<lshbox::Matrix<DATATYPE>::Accessor> scanner( accessor, metric, K ); for (unsigned i = 0; i != size; ++i) { lsh.query(quy + i * data.getDim(), scanner); std::vector<std::pair<float, unsigned> > tmp = scanner.topk().getTopk(); for (unsigned j = 0; j != tmp.size(); ++j) { indices[i * K + j] = tmp[j].second; dists[i * K + j] = tmp[j].first; } } }
void AirspaceNearestSort::populate_queue(const Airspaces &airspaces, const fixed range) { AirspacesInterface::AirspaceVector vectors = airspaces.scan_range(m_location, range, m_condition); for (auto v = vectors.begin(); v != vectors.end(); ++v) { const AbstractAirspace *as = v->get_airspace(); if (as != NULL) { const AirspaceInterceptSolution ais = solve_intercept(*as); const fixed value = metric(ais); if (!negative(value)) { m_q.push(std::make_pair(m_reverse? -value:value, std::make_pair(ais, *v))); } } } }
void MapWidget::paintEvent(QPaintEvent *e) { Q_UNUSED(e) QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.drawImage( rect(), p->image, p->image.rect() ); if( p->image_loaded ) { painter.drawImage( QRect(width()/2-MAP_PIN_WIDTH/2, height()/2-MAP_PIN_WIDTH,MAP_PIN_WIDTH,MAP_PIN_WIDTH), *map_widget_pin, map_widget_pin->rect() ); } else { const QString & text = (p->reply? tr("Loading") : tr("No Position")); QFontMetrics metric( painter.font() ); painter.drawText( QRect(0,height()-metric.height(),width(),metric.height()), Qt::AlignCenter | Qt::AlignVCenter, text ); } }
TEST(BaseHamiltonian, update) { std::fstream data_stream(std::string("").c_str(), std::fstream::in); stan::io::dump data_var_context(data_stream); data_stream.close(); funnel_namespace::funnel model(data_var_context, &std::cout); stan::mcmc::mock_hamiltonian<funnel_namespace::funnel, rng_t> metric(model, &std::cout); stan::mcmc::ps_point z(11); z.q.setOnes(); metric.update(z); EXPECT_FLOAT_EQ(10.73223197, z.V); EXPECT_FLOAT_EQ(8.757758279, z.g(0)); for (int i = 1; i < z.q.size(); ++i) EXPECT_FLOAT_EQ(0.1353352832, z.g(i)); }
TEST(McmcDenseEMetric, streams) { stan::test::capture_std_streams(); rng_t base_rng(0); Eigen::VectorXd q(2); q(0) = 5; q(1) = 1; stan::mcmc::mock_model model(q.size()); // typedef to use within Google Test macros typedef stan::mcmc::dense_e_metric<stan::mcmc::mock_model, rng_t> dense_e; EXPECT_NO_THROW(dense_e metric(model)); stan::test::reset_std_streams(); EXPECT_EQ("", stan::test::cout_ss.str()); EXPECT_EQ("", stan::test::cerr_ss.str()); }
MessageNotification::MessageNotification(QString message, int hide_in_msec) : CoreUi::NotificationBaseWidget(hide_in_msec, message) { // Init Ui QPlainTextEdit *message_box = new QPlainTextEdit(message); message_box->setReadOnly(true); message_box->setFrameShape(QFrame::NoFrame); QFontMetrics metric(message_box->font()); QRect text_rect = metric.boundingRect(QRect(0,0,160,400), Qt::AlignLeft|Qt::TextWordWrap, message); message_box->setMaximumHeight(text_rect.height() + metric.height()); message_box->setMinimumHeight(text_rect.height() + metric.height()); // Layout QWidget *content_widget = new QWidget(); QVBoxLayout *v_layout = new QVBoxLayout(); v_layout->addWidget(message_box); content_widget->setLayout(v_layout); SetCentralWidget(content_widget); }
int main(int argc, char *argv[]) { if (argc < 3 || argc > 5) { std::cerr << "Usage: ./create_benchmark data_file benchmark_file [Q = 200] [K = 50]" << std::endl; return -1; } unsigned K = 50, Q = 200, seed = 2; if (argc > 3) { Q = atoi(argv[3]); } if (argc > 4) { K = atoi(argv[4]); } lshbox::timer timer; std::cout << "CREATE BENCHMARK FOR DATA ..." << std::endl; timer.restart(); std::string file(argv[1]); std::string query_file(argv[2]); lshbox::Matrix<float> data(file); lshbox::Benchmark bench; bench.init(Q, K, data.getSize(), seed); lshbox::Metric<float> metric(data.getDim(), L2_DIST); lshbox::progress_display pd(Q); for (unsigned i = 0; i != Q; ++i) { unsigned q = bench.getQuery(i); lshbox::Topk &topk = bench.getAnswer(i); for (unsigned j = 0; j != data.getSize(); ++j) { topk.push(j, metric.dist(data[q], data[j])); } topk.genTopk(); ++pd; } bench.save(query_file); std::cout << "MEAN QUERY TIME: " << timer.elapsed() / Q << "s." << std::endl; }
void ObjectiveFunctionTests::test_clone( ObjectiveFunctionTemplate* of ) { const double some_vals[] = { 1, 2, 3, 4, 5, 6, 0.5 }; const unsigned num_vals = sizeof(some_vals)/sizeof(some_vals[0]); OFTestQM metric( some_vals, num_vals ); of->set_quality_metric(&metric); // test that we get the same value from both auto_ptr<ObjectiveFunction> of2( of->clone() ); double exp_val, val; exp_val = evaluate_internal( ObjectiveFunction::CALCULATE, EVAL, of ); val = evaluate_internal( ObjectiveFunction::CALCULATE, EVAL, of2.get() ); CPPUNIT_ASSERT_DOUBLES_EQUAL( exp_val, val, 1e-12 ); // check if OF supports BCD -- if not then done MsqError err; of->evaluate( ObjectiveFunction::UPDATE, patch(), val, false, err ); if (err) { err.clear(); return; } // build up some saved state in the objective function of->clear(); const double vals1[] = { 1.0, 3.0, 4.0, 8.0 }; const size_t vals1_len = sizeof(vals1)/sizeof(vals1[0]); const double vals2[] = { 21.5, 11.1, 30.0, 0.5 }; const size_t vals2_len = sizeof(vals2)/sizeof(vals2[0]); metric.set_values( vals1, vals1_len ); evaluate_internal( ObjectiveFunction::SAVE, EVAL, of ); metric.append_values( vals2, vals2_len ); evaluate_internal( ObjectiveFunction::ACCUMULATE, EVAL, of ); // check that clone has same accumulated data of2 = auto_ptr<ObjectiveFunction>(of->clone()); metric.set_values( some_vals, num_vals ); exp_val = evaluate_internal( ObjectiveFunction::UPDATE, EVAL, of ); val = evaluate_internal( ObjectiveFunction::UPDATE, EVAL, of2.get() ); CPPUNIT_ASSERT_DOUBLES_EQUAL( exp_val, val, 1e-12 ); }
/** * Initialise vim to use the font "font_name". If it's NULL, pick a default * font. * If "fontset" is TRUE, load the "font_name" as a fontset. * Return FAIL if the font could not be loaded, OK otherwise. */ int gui_mch_init_font(char_u *font_name, int do_fontset) { QFont *qf = gui_mch_get_font(font_name, FALSE); if ( qf == NULL ) { return FAIL; } QFontMetrics metric( *qf ); if ( VimWrapper::isFakeMonospace(*qf) || getenv("QVIM_DRAW_STRING_SLOW") ) { vimshell->setSlowStringDrawing( true ); } else { vimshell->setSlowStringDrawing( false ); } gui.norm_font = qf; update_char_metrics(metric); vimshell->setCharWidth(gui.char_width); return OK; }
void MetricBackend_AMD_perfmon::freeMonitor(unsigned monitorId) { unsigned monitor = monitors[monitorId]; GLuint dataAvail = 0; GLuint size; glFlush(); while (!dataAvail) { glGetPerfMonitorCounterDataAMD(monitor, GL_PERFMON_RESULT_AVAILABLE_AMD, sizeof(GLuint), &dataAvail, nullptr); } glGetPerfMonitorCounterDataAMD(monitor, GL_PERFMON_RESULT_SIZE_AMD, sizeof(GLuint), &size, nullptr); // collect data unsigned* buf = collector.newDataBuffer(monitorEvent[monitorId], size/sizeof(unsigned)); glGetPerfMonitorCounterDataAMD(monitor, GL_PERFMON_RESULT_AMD, size, buf, nullptr); /* populate metricOffsets */ if (metricOffsets.size() < curPass + 1) { std::map<std::pair<unsigned, unsigned>, unsigned> pairOffsets; unsigned offset = 0; unsigned id, gid; for (int k = 0; k < passes[curPass].size(); k++) { gid = buf[offset++]; id = buf[offset++]; pairOffsets[std::make_pair(gid, id)] = offset; Metric_AMD_perfmon metric(gid, id); offset += metric.size() / sizeof(unsigned); } // translate to existing metrics in passes variable std::map<Metric_AMD_perfmon*, unsigned> temp; for (auto &m : passes[curPass]) { id = m.id(); gid = m.groupId(); temp[&m] = pairOffsets[std::make_pair(gid, id)]; } metricOffsets.push_back(std::move(temp)); } }
Token::Token( const QString &name, const QString &iconName, int value, QWidget *parent ) : QWidget( parent ) , m_name( name ) , m_icon( KIcon( iconName ) ) , m_iconName( iconName ) , m_value( value ) { setAttribute( Qt::WA_Hover ); if ( parent ) { if ( TokenDropTarget *editWidget = qobject_cast<TokenDropTarget*>( parent ) ) connect( this, SIGNAL(changed()), editWidget, SIGNAL(changed()) ); } m_label = new QLabel( this ); m_label->setAlignment( Qt::AlignCenter ); m_label->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); m_label->setText( name ); QHBoxLayout *hlayout = new QHBoxLayout( this ); setLayout( hlayout ); m_iconContainer = new QLabel( this ); m_iconContainer->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ); QPixmap pixmap = QPixmap( icon().pixmap( 16, 16 ) ); m_iconContainer->setPixmap( pixmap ); setContentsMargins( 4, 2, 4, 2 ); hlayout->setContentsMargins( 0, 0, 0, 0 ); hlayout->addWidget( m_iconContainer ); hlayout->addWidget( m_label ); QFontMetrics metric( font() ); QSizePolicy sizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); m_label->setSizePolicy( sizePolicy ); m_iconContainer->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ) ); }
void KisTextBrush::updateBrush() { QFontMetrics metric(m_font); int w = metric.width(m_txt); int h = metric.height(); // don't crash, if there is no text if (w==0) w=1; if (h==0) h=1; QPixmap px(w, h); QPainter p; p.begin(&px); p.setFont(m_font); p.fillRect(0, 0, w, h, Qt::white); p.setPen(Qt::black); p.drawText(0, metric.ascent(), m_txt); p.end(); setImage(px.toImage()); setValid(true); resetBoundary(); }
void query(scalar *quy, unsigned size, scalar *indices, scalar *dists, unsigned type, unsigned K) { Matrix<scalar>::Accessor accessor(data); Metric<scalar> metric(data.getDim(), type); Scanner<lshbox::Matrix<scalar>::Accessor> scanner( accessor, metric, K ); for (unsigned i = 0; i != size; ++i) { scanner.reset(quy + i * data.getDim()); lsh.query(quy + i * data.getDim(), scanner); scanner.topk().genTopk(); std::vector<std::pair<double, unsigned> > tmp = scanner.topk().getTopk(); for (unsigned j = 0; j != tmp.size(); ++j) { indices[i * K + j] = tmp[j].second; dists[i * K + j] = tmp[j].first; } } }
/** * Initialise vim to use the font "font_name". If it's NULL, pick a default * font. * If "fontset" is TRUE, load the "font_name" as a fontset. * Return FAIL if the font could not be loaded, OK otherwise. */ int gui_mch_init_font(char_u *font_name, int do_fontset) { QFont *qf = gui_mch_get_font(font_name, TRUE); if ( qf == NULL ) { return FAIL; } QFontMetrics metric( *qf ); if ( metric.averageCharWidth() != metric.maxWidth() ) { qDebug() << "Warning, fake monospace font?"; } gui.norm_font = qf; gui.char_width = metric.width("M"); gui.char_height = metric.height(); gui.char_ascent = metric.ascent(); vimshell->setCharWidth(gui.char_width); return OK; }
TEST(McmcDiagEMetric, sample_p) { rng_t base_rng(0); Eigen::VectorXd q(2); q(0) = 5; q(1) = 1; std::stringstream metric_output; stan::mcmc::mock_model model(q.size()); stan::mcmc::diag_e_metric<stan::mcmc::mock_model, rng_t> metric(model, &metric_output); stan::mcmc::diag_e_point z(q.size()); int n_samples = 1000; double m = 0; double m2 = 0; for (int i = 0; i < n_samples; ++i) { metric.sample_p(z, base_rng); double T = metric.T(z); double delta = T - m; m += delta / static_cast<double>(i + 1); m2 += delta * (T - m); } double var = m2 / (n_samples + 1.0); // Mean within 5sigma of expected value (d / 2) EXPECT_EQ(true, fabs(m - 0.5 * q.size()) < 5.0 * sqrt(var)); // Variance within 10% of expected value (d / 2) EXPECT_EQ(true, fabs(var - 0.5 * q.size()) < 0.1 * q.size()); EXPECT_EQ("", metric_output.str()); }
void BlackEdgeTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if (text.isEmpty()) return; painter->setRenderHint(QPainter::Antialiasing); if (outline > 0) { QPen pen(Qt::black); pen.setWidth(outline); painter->setPen(pen); } QFontMetrics metric(font); int height = metric.height() - metric.descent() + skip; int i; for (i = 0; i < text.length(); i++) { QString text; text.append(this->text.at(i)); QPainterPath path; path.addText(0, (i + 1) * height, font, text); if (outline > 0) painter->drawPath(path); painter->fillPath(path, color); } if (hasFocus()) { QPen red_pen(Qt::red); painter->setPen(red_pen); QRectF rect = boundingRect(); painter->drawRect(-1, -1, rect.width() + 2, rect.height() + 2); } }
//! [0] DragLabel::DragLabel(const QString &text, QWidget *parent) : QLabel(parent) { QFontMetrics metric(font()); QSize size = metric.size(Qt::TextSingleLine, text); QImage image(size.width() + 12, size.height() + 12, QImage::Format_ARGB32_Premultiplied); image.fill(qRgba(0, 0, 0, 0)); QFont font; font.setStyleStrategy(QFont::ForceOutline); //! [0] //! [1] QLinearGradient gradient(0, 0, 0, image.height()-1); gradient.setColorAt(0.0, Qt::white); gradient.setColorAt(0.2, QColor(200, 200, 255)); gradient.setColorAt(0.8, QColor(200, 200, 255)); gradient.setColorAt(1.0, QColor(127, 127, 200)); QPainter painter; painter.begin(&image); painter.setRenderHint(QPainter::Antialiasing); painter.setBrush(gradient); painter.drawRoundedRect(QRectF(0.5, 0.5, image.width()-1, image.height()-1), 25, 25, Qt::RelativeSize); painter.setFont(font); painter.setBrush(Qt::black); painter.drawText(QRect(QPoint(6, 6), size), Qt::AlignCenter, text); painter.end(); //! [1] //! [2] setPixmap(QPixmap::fromImage(image)); m_labelText = text; }
QPixmap FixedWidthTableView::getDragPixmap(QString text) { // From the "Fridge Magnets" example QFontMetrics metric(font()); QSize size = metric.size(Qt::TextSingleLine, text); QImage image(size.width() + 12, size.height() + 12, QImage::Format_ARGB32_Premultiplied); image.fill(qRgba(0, 0, 0, 0)); QFont font; font.setStyleStrategy(QFont::ForceOutline); QPainter painter; painter.begin(&image); painter.setRenderHint(QPainter::Antialiasing); painter.setFont(font); painter.setBrush(Qt::black); painter.drawText(QRect(QPoint(6, 6), size), Qt::AlignCenter, text); painter.end(); return QPixmap::fromImage(image); }
int MetricBackend_AMD_perfmon::enableMetric(Metric* metric_, QueryBoundary pollingRule) { unsigned id = metric_->id(); unsigned gid = metric_->groupId(); unsigned monitor; // profiling only draw calls if (pollingRule == QUERY_BOUNDARY_CALL) return 1; // check that Metric is valid metric glGenPerfMonitorsAMD(1, &monitor); glGetError(); glSelectPerfMonitorCountersAMD(monitor, 1, gid, 1, &id); GLenum err = glGetError(); glDeletePerfMonitorsAMD(1, &monitor); if (err == GL_INVALID_VALUE) { return 1; } Metric_AMD_perfmon metric(gid, id); metric.numType(); // triggers metric vars precache (in case context changes) metrics[pollingRule].push_back(metric); return 0; }
///Delegate painter void ImDelegates::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { Q_ASSERT(index.isValid()); QPixmap icon = index.data(Qt::DecorationRole).value<QPixmap>(); int icnWidth = 50; if (!icon.isNull()) { painter->drawPixmap(option.rect.x()+5,option.rect.y()+(option.rect.height()/2)-(icon.height()/2),icon); icnWidth = icon.width(); } QFontMetrics metric(painter->font()); QString text = index.data(Qt::DisplayRole).toString(); QRect requiredRect = metric.boundingRect(option.rect.x()+icnWidth+10,option.rect.y()+metric.height()+5,option.rect.width() - icnWidth - 10 /*margin*/,500,Qt::TextWordWrap|Qt::AlignLeft,text); painter->drawText(requiredRect,Qt::AlignLeft|Qt::TextWordWrap,text); QFont font = painter->font(); font.setBold(true); painter->setFont(font); const QString peerName = index.data((int)Media::TextRecording::Role::AuthorDisplayname).toString(); painter->drawText(option.rect.x()+icnWidth+10,option.rect.y()+metric.height(), peerName); font.setBold(false); painter->setFont(font); }
void ObjectiveFunctionTests::test_handles_qm_error( OFTestMode test_mode, ObjectiveFunctionTemplate* of ) { OFTestBadQM metric(true); of->set_quality_metric( &metric ); MsqError err; vector<Vector3D> grad; vector<SymMatrix3D> diag; MsqHessian hess; double result; bool valid; switch (test_mode) { case EVAL: valid = of->evaluate( ObjectiveFunction::CALCULATE, patch(), result, OF_FREE_EVALS_ONLY, err ); break; case GRAD: valid = of->evaluate_with_gradient( ObjectiveFunction::CALCULATE, patch(), result, grad, err ); break; case DIAG: valid = of->evaluate_with_Hessian_diagonal( ObjectiveFunction::CALCULATE, patch(), result, grad, diag, err ); break; case HESS: hess.initialize( patch(), err ); ASSERT_NO_ERROR( err ); valid = of->evaluate_with_Hessian( ObjectiveFunction::CALCULATE, patch(), result, grad, hess, err ); break; default: CPPUNIT_ASSERT(false); } CPPUNIT_ASSERT(err); }
int DhQGLWidget::Dvhmetric(long x1) const { return metric((QPaintDevice::PaintDeviceMetric)x1); }
void VVimIndicator::setupUI() { m_cmdLineEdit = new VVimCmdLineEdit(this); m_cmdLineEdit->setProperty("VimCommandLine", true); connect(m_cmdLineEdit, &VVimCmdLineEdit::commandCancelled, this, [this](){ if (m_editTab) { m_editTab->focusTab(); } // NOTICE: m_cmdLineEdit should not hide itself before setting // focus to edit tab. m_cmdLineEdit->hide(); if (m_vim) { m_vim->processCommandLineCancelled(); } }); connect(m_cmdLineEdit, &VVimCmdLineEdit::commandFinished, this, [this](VVim::CommandLineType p_type, const QString &p_cmd){ if (m_editTab) { m_editTab->focusTab(); } m_cmdLineEdit->hide(); // Hide the cmd line edit before execute the command. // If we execute the command first, we will get Chinese input // method enabled after returning to read mode. if (m_vim) { m_vim->processCommandLine(p_type, p_cmd); } }); connect(m_cmdLineEdit, &VVimCmdLineEdit::commandChanged, this, [this](VVim::CommandLineType p_type, const QString &p_cmd){ if (m_vim) { m_vim->processCommandLineChanged(p_type, p_cmd); } }); connect(m_cmdLineEdit, &VVimCmdLineEdit::requestNextCommand, this, [this](VVim::CommandLineType p_type, const QString &p_cmd){ if (m_vim) { QString cmd = m_vim->getNextCommandHistory(p_type, p_cmd); if (!cmd.isNull()) { m_cmdLineEdit->setCommand(cmd); } else { m_cmdLineEdit->restoreUserLastInput(); } } }); connect(m_cmdLineEdit, &VVimCmdLineEdit::requestPreviousCommand, this, [this](VVim::CommandLineType p_type, const QString &p_cmd){ if (m_vim) { QString cmd = m_vim->getPreviousCommandHistory(p_type, p_cmd); if (!cmd.isNull()) { m_cmdLineEdit->setCommand(cmd); } } }); connect(m_cmdLineEdit, &VVimCmdLineEdit::requestRegister, this, [this](int p_key, int p_modifiers){ if (m_vim) { QString val = m_vim->readRegister(p_key, p_modifiers); if (!val.isEmpty()) { m_cmdLineEdit->setText(m_cmdLineEdit->text() + val); } } }); m_cmdLineEdit->hide(); m_modeLabel = new QLabel(this); m_modeLabel->setProperty("VimIndicatorModeLabel", true); QTreeWidget *regTree = new QTreeWidget(this); regTree->setProperty("ItemBorder", true); regTree->setRootIsDecorated(false); regTree->setColumnCount(2); regTree->header()->setStretchLastSection(true); QStringList headers; headers << tr("Register") << tr("Value"); regTree->setHeaderLabels(headers); m_regBtn = new VButtonWithWidget("\"", regTree, this); m_regBtn->setToolTip(tr("Registers")); m_regBtn->setProperty("StatusBtn", true); m_regBtn->setFocusPolicy(Qt::NoFocus); connect(m_regBtn, &VButtonWithWidget::popupWidgetAboutToShow, this, &VVimIndicator::updateRegistersTree); QTreeWidget *markTree = new QTreeWidget(this); markTree->setProperty("ItemBorder", true); markTree->setRootIsDecorated(false); markTree->setColumnCount(4); markTree->header()->setStretchLastSection(true); headers.clear(); headers << tr("Mark") << tr("Line") << tr("Column") << tr("Text"); markTree->setHeaderLabels(headers); m_markBtn = new VButtonWithWidget("[]", markTree, this); m_markBtn->setToolTip(tr("Marks")); m_markBtn->setProperty("StatusBtn", true); m_markBtn->setFocusPolicy(Qt::NoFocus); connect(m_markBtn, &VButtonWithWidget::popupWidgetAboutToShow, this, &VVimIndicator::updateMarksTree); m_keyLabel = new QLabel(this); m_keyLabel->setProperty("VimIndicatorKeyLabel", true); QFontMetrics metric(font()); m_keyLabel->setMinimumWidth(metric.width('A') * 5); QHBoxLayout *mainLayout = new QHBoxLayout(this); mainLayout->addStretch(); mainLayout->addWidget(m_cmdLineEdit); mainLayout->addWidget(m_modeLabel); mainLayout->addWidget(m_regBtn); mainLayout->addWidget(m_markBtn); mainLayout->addWidget(m_keyLabel); mainLayout->setContentsMargins(0, 0, 0, 0); setLayout(mainLayout); }
void ClipObject::loadCaption(QString ct, QFont cf, QColor cc, QColor chc) { m_captionText = ct; m_captionFont = cf; m_captionColor = cc; m_captionHaloColor = chc; if (m_captionText.isEmpty()) { m_captionPresent = false; return; } QFontMetrics metric(m_captionFont); int mde = metric.descent(); int fht = metric.height(); int fwd = metric.width(m_captionText)+2; //------------------- QImage bImage = QImage(fwd, fht, QImage::Format_ARGB32); bImage.fill(0); { QPainter bpainter(&bImage); // we have image as ARGB, but we want RGBA // so switch red and blue colors here itself QColor penColor(m_captionHaloColor.blue(), m_captionHaloColor.green(), m_captionHaloColor.red()); // do not use alpha(), // opacity will be modulated using clip-plane's opacity parameter bpainter.setPen(penColor); bpainter.setFont(m_captionFont); bpainter.drawText(1, fht-mde, m_captionText); uchar *dbits = new uchar[4*fht*fwd]; uchar *bits = bImage.bits(); memcpy(dbits, bits, 4*fht*fwd); for(int i=2; i<fht-2; i++) for(int j=2; j<fwd-2; j++) { for (int k=0; k<4; k++) { int sum = 0; for(int i0=-2; i0<=2; i0++) for(int j0=-2; j0<=2; j0++) sum += dbits[4*((i+i0)*fwd+(j+j0)) + k]; bits[4*(i*fwd+j) + k] = sum/25; } } delete [] dbits; } //------------------- QImage cImage = QImage(fwd, fht, QImage::Format_ARGB32); cImage.fill(0); QPainter cpainter(&cImage); // first draw the halo image cpainter.drawImage(0, 0, bImage); // we have image as ARGB, but we want RGBA // so switch red and blue colors here itself QColor penColor(m_captionColor.blue(), m_captionColor.green(), m_captionColor.red()); // do not use alpha(), // opacity will be modulated using clip-plane's opacity parameter cpainter.setPen(penColor); cpainter.setFont(m_captionFont); cpainter.drawText(1, fht-mde, m_captionText); m_textureWidth = fwd; m_textureHeight = fht; unsigned char *image = new unsigned char[4*m_textureWidth*m_textureHeight]; memcpy(image, cImage.bits(), 4*m_textureWidth*m_textureHeight); if (m_imageTex) glDeleteTextures(1, &m_imageTex); glGenTextures(1, &m_imageTex); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, m_imageTex); glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 4, m_textureWidth, m_textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); glDisable(GL_TEXTURE_RECTANGLE_ARB); delete [] image; clearImage(); m_captionPresent = true; }
int QPrinter::metric(int m) const { int val = 1; switch (m) { case QPaintDeviceMetrics::PdmWidth: { bool orientInSync = true; PMOrientation o; QPrinter::Orientation tmpOrient = orientation(); if (PMGetOrientation(pformat, &o) == noErr) { orientInSync = ((o == kPMPortrait && tmpOrient == Portrait) || o == kPMLandscape && tmpOrient == Landscape); } PageSize s = pageSize(); if (s >= QPrinter::Custom) { val = tmpOrient == Portrait ? customPaperSize_.width() : customPaperSize_.height(); } else { if (state == PST_ACTIVE || (tmpOrient == Portrait || orientInSync)) { val = qt_get_PDMWidth(pformat, fullPage()); } else { val = qt_get_PDMHeight(pformat, fullPage()); } } break; } case QPaintDeviceMetrics::PdmHeight: { bool orientInSync = true; PMOrientation o; QPrinter::Orientation tmpOrient = orientation(); if (PMGetOrientation(pformat, &o) == noErr) { orientInSync = ((o == kPMPortrait && tmpOrient == Portrait) || o == kPMLandscape && tmpOrient == Landscape); } PageSize s = pageSize(); if (s >= QPrinter::Custom) { val = tmpOrient == Portrait ? customPaperSize_.height() : customPaperSize_.width(); } else { if (state == PST_ACTIVE || (tmpOrient == Portrait || orientInSync)) { val = qt_get_PDMHeight(pformat, fullPage()); } else { val = qt_get_PDMWidth(pformat, fullPage()); } } break; } // We don't have to worry about the printer state here as metric() does that for us. case QPaintDeviceMetrics::PdmWidthMM: val = metric(QPaintDeviceMetrics::PdmWidth); val = (val * 254 + 5 * res) / (10 * res); break; case QPaintDeviceMetrics::PdmHeightMM: val = metric(QPaintDeviceMetrics::PdmHeight); val = (val * 254 + 5 * res) / (10 * res); break; case QPaintDeviceMetrics::PdmPhysicalDpiX: case QPaintDeviceMetrics::PdmPhysicalDpiY: { PMPrinter printer; if (PMSessionGetCurrentPrinter(psession, &printer) == noErr) { PMResolution resolution; PMPrinterGetPrinterResolution(printer, kPMCurrentValue, &resolution); val = (int)resolution.vRes; break; } //otherwise fall through } case QPaintDeviceMetrics::PdmDpiY: case QPaintDeviceMetrics::PdmDpiX: val = res; break; case QPaintDeviceMetrics::PdmNumColors: val = (1 << metric(QPaintDeviceMetrics::PdmDepth)); break; case QPaintDeviceMetrics::PdmDepth: val = 24; break; default: val = 0; #if defined(QT_CHECK_RANGE) qWarning("Qt: QPixmap::metric: Invalid metric command"); #endif } return val; }
int DhQPushButton::Dvhmetric(long x1) const { return metric((QPaintDevice::PaintDeviceMetric)x1); }
int DhQAbstractSpinBox::Dvhmetric(long x1) const { return metric((QPaintDevice::PaintDeviceMetric)x1); }
TEST(McmcDiagEMetric, gradients) { rng_t base_rng(0); Eigen::VectorXd q = Eigen::VectorXd::Ones(11); stan::mcmc::diag_e_point z(q.size()); z.q = q; z.p.setOnes(); std::fstream data_stream(std::string("").c_str(), std::fstream::in); stan::io::dump data_var_context(data_stream); data_stream.close(); std::stringstream model_output, metric_output; funnel_model_namespace::funnel_model model(data_var_context, &model_output); stan::mcmc::diag_e_metric<funnel_model_namespace::funnel_model, rng_t> metric(model, &metric_output); double epsilon = 1e-6; metric.update(z); Eigen::VectorXd g1 = metric.dtau_dq(z); for (int i = 0; i < z.q.size(); ++i) { double delta = 0; z.q(i) += epsilon; metric.update(z); delta += metric.tau(z); z.q(i) -= 2 * epsilon; metric.update(z); delta -= metric.tau(z); z.q(i) += epsilon; metric.update(z); delta /= 2 * epsilon; EXPECT_NEAR(delta, g1(i), epsilon); } Eigen::VectorXd g2 = metric.dtau_dp(z); for (int i = 0; i < z.q.size(); ++i) { double delta = 0; z.p(i) += epsilon; delta += metric.tau(z); z.p(i) -= 2 * epsilon; delta -= metric.tau(z); z.p(i) += epsilon; delta /= 2 * epsilon; EXPECT_NEAR(delta, g2(i), epsilon); } Eigen::VectorXd g3 = metric.dphi_dq(z); for (int i = 0; i < z.q.size(); ++i) { double delta = 0; z.q(i) += epsilon; metric.update(z); delta += metric.phi(z); z.q(i) -= 2 * epsilon; metric.update(z); delta -= metric.phi(z); z.q(i) += epsilon; metric.update(z); delta /= 2 * epsilon; EXPECT_NEAR(delta, g3(i), epsilon); } EXPECT_EQ("", model_output.str()); EXPECT_EQ("", metric_output.str()); }
int DhQGroupBox::Dvhmetric(long x1) const { return metric((QPaintDevice::PaintDeviceMetric)x1); }
TEST(McmcUnitENuts, tree_boundary_test) { rng_t base_rng(4839294); stan::mcmc::unit_e_point z_init(3); z_init.q(0) = 1; z_init.q(1) = -1; z_init.q(2) = 1; z_init.p(0) = -1; z_init.p(1) = 1; z_init.p(2) = -1; std::stringstream output; stan::interface_callbacks::writer::stream_writer writer(output); std::stringstream error_stream; stan::interface_callbacks::writer::stream_writer error_writer(error_stream); std::fstream empty_stream("", std::fstream::in); stan::io::dump data_var_context(empty_stream); typedef gauss3D_model_namespace::gauss3D_model model_t; model_t model(data_var_context); // Compute expected tree boundaries typedef stan::mcmc::unit_e_metric<model_t, rng_t> metric_t; metric_t metric(model); stan::mcmc::expl_leapfrog<metric_t> unit_e_integrator; double epsilon = 0.1; stan::mcmc::unit_e_point z_test = z_init; metric.init(z_test, writer, error_writer); unit_e_integrator.evolve(z_test, metric, epsilon, writer, error_writer); Eigen::VectorXd p_sharp_forward_1 = metric.dtau_dp(z_test); unit_e_integrator.evolve(z_test, metric, epsilon, writer, error_writer); Eigen::VectorXd p_sharp_forward_2 = metric.dtau_dp(z_test); unit_e_integrator.evolve(z_test, metric, epsilon, writer, error_writer); unit_e_integrator.evolve(z_test, metric, epsilon, writer, error_writer); Eigen::VectorXd p_sharp_forward_3 = metric.dtau_dp(z_test); unit_e_integrator.evolve(z_test, metric, epsilon, writer, error_writer); unit_e_integrator.evolve(z_test, metric, epsilon, writer, error_writer); unit_e_integrator.evolve(z_test, metric, epsilon, writer, error_writer); unit_e_integrator.evolve(z_test, metric, epsilon, writer, error_writer); Eigen::VectorXd p_sharp_forward_4 = metric.dtau_dp(z_test); z_test = z_init; metric.init(z_test, writer, error_writer); unit_e_integrator.evolve(z_test, metric, -epsilon, writer, error_writer); Eigen::VectorXd p_sharp_backward_1 = metric.dtau_dp(z_test); unit_e_integrator.evolve(z_test, metric, -epsilon, writer, error_writer); Eigen::VectorXd p_sharp_backward_2 = metric.dtau_dp(z_test); unit_e_integrator.evolve(z_test, metric, -epsilon, writer, error_writer); unit_e_integrator.evolve(z_test, metric, -epsilon, writer, error_writer); Eigen::VectorXd p_sharp_backward_3 = metric.dtau_dp(z_test); unit_e_integrator.evolve(z_test, metric, -epsilon, writer, error_writer); unit_e_integrator.evolve(z_test, metric, -epsilon, writer, error_writer); unit_e_integrator.evolve(z_test, metric, -epsilon, writer, error_writer); unit_e_integrator.evolve(z_test, metric, -epsilon, writer, error_writer); Eigen::VectorXd p_sharp_backward_4 = metric.dtau_dp(z_test); // Check expected tree boundaries to those dynamically geneated by NUTS stan::mcmc::unit_e_nuts<model_t, rng_t> sampler(model, base_rng); sampler.set_nominal_stepsize(epsilon); sampler.set_stepsize_jitter(0); sampler.sample_stepsize(); stan::mcmc::ps_point z_propose = z_init; Eigen::VectorXd p_sharp_left = Eigen::VectorXd::Zero(z_init.p.size()); Eigen::VectorXd p_sharp_right = Eigen::VectorXd::Zero(z_init.p.size()); Eigen::VectorXd rho = z_init.p; double log_sum_weight = -std::numeric_limits<double>::infinity(); double H0 = -0.1; int n_leapfrog = 0; double sum_metro_prob = 0; // Depth 0 forward sampler.z() = z_init; sampler.init_hamiltonian(writer, error_writer); sampler.build_tree(0, z_propose, p_sharp_left, p_sharp_right, rho, H0, 1, n_leapfrog, log_sum_weight, sum_metro_prob, writer, error_writer); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_forward_1(n), p_sharp_left(n)); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_forward_1(n), p_sharp_right(n)); // Depth 1 forward sampler.z() = z_init; sampler.init_hamiltonian(writer, error_writer); sampler.build_tree(1, z_propose, p_sharp_left, p_sharp_right, rho, H0, 1, n_leapfrog, log_sum_weight, sum_metro_prob, writer, error_writer); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_forward_1(n), p_sharp_left(n)); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_forward_2(n), p_sharp_right(n)); // Depth 2 forward sampler.z() = z_init; sampler.init_hamiltonian(writer, error_writer); sampler.build_tree(2, z_propose, p_sharp_left, p_sharp_right, rho, H0, 1, n_leapfrog, log_sum_weight, sum_metro_prob, writer, error_writer); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_forward_1(n), p_sharp_left(n)); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_forward_3(n), p_sharp_right(n)); // Depth 3 forward sampler.z() = z_init; sampler.init_hamiltonian(writer, error_writer); sampler.build_tree(3, z_propose, p_sharp_left, p_sharp_right, rho, H0, 1, n_leapfrog, log_sum_weight, sum_metro_prob, writer, error_writer); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_forward_1(n), p_sharp_left(n)); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_forward_4(n), p_sharp_right(n)); // Depth 0 backward sampler.z() = z_init; sampler.init_hamiltonian(writer, error_writer); sampler.build_tree(0, z_propose, p_sharp_left, p_sharp_right, rho, H0, -1, n_leapfrog, log_sum_weight, sum_metro_prob, writer, error_writer); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_backward_1(n), p_sharp_left(n)); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_backward_1(n), p_sharp_right(n)); // Depth 1 backward sampler.z() = z_init; sampler.init_hamiltonian(writer, error_writer); sampler.build_tree(1, z_propose, p_sharp_left, p_sharp_right, rho, H0, -1, n_leapfrog, log_sum_weight, sum_metro_prob, writer, error_writer); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_backward_1(n), p_sharp_left(n)); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_backward_2(n), p_sharp_right(n)); // Depth 2 backward sampler.z() = z_init; sampler.init_hamiltonian(writer, error_writer); sampler.build_tree(2, z_propose, p_sharp_left, p_sharp_right, rho, H0, -1, n_leapfrog, log_sum_weight, sum_metro_prob, writer, error_writer); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_backward_1(n), p_sharp_left(n)); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_backward_3(n), p_sharp_right(n)); // Depth 3 backward sampler.z() = z_init; sampler.init_hamiltonian(writer, error_writer); sampler.build_tree(3, z_propose, p_sharp_left, p_sharp_right, rho, H0, -1, n_leapfrog, log_sum_weight, sum_metro_prob, writer, error_writer); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_backward_1(n), p_sharp_left(n)); for (int n = 0; n < rho.size(); ++n) EXPECT_FLOAT_EQ(p_sharp_backward_4(n), p_sharp_right(n)); }