Example #1
0
void ProgressBar::paintEvent(QPaintEvent *)
{
    // TODO move font into Utils::StyleHelper
    // TODO use Utils::StyleHelper white

    double range = maximum() - minimum();
    double percent = 0.50;
    if (range != 0)
        percent = (value() - minimum()) / range;
    if (percent > 1)
        percent = 1;
    else if (percent < 0)
        percent = 0;

    QPainter p(this);
    QFont boldFont(p.font());
    boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
    boldFont.setBold(true);
    p.setFont(boldFont);
    QFontMetrics fm(boldFont);

    // Draw separator
    int h = fm.height();
    p.setPen(QColor(0, 0, 0, 70));
    p.drawLine(0,0, size().width(), 0);

    p.setPen(QColor(255, 255, 255, 70));
    p.drawLine(0, 1, size().width(), 1);

    QRect textRect = rect().adjusted(0, 0, -1, 0);
    textRect.setHeight(h+5);

    p.setPen(QColor(30, 30, 30, 80));
    p.drawText(textRect, Qt::AlignHCenter | Qt::AlignBottom, m_title);
    p.translate(0, -1);
    p.setPen(Utils::StyleHelper::panelTextColor());
    p.drawText(textRect, Qt::AlignHCenter | Qt::AlignBottom, m_title);
    p.translate(0, 1);

    m_progressHeight = PROGRESSBAR_HEIGHT;
    m_progressHeight += ((m_progressHeight % 2) + 1) % 2; // make odd
    // draw outer rect
    QRect rect(INDENT - 1, h+6, size().width()-2*INDENT, m_progressHeight-1);
    p.setPen(Utils::StyleHelper::panelTextColor());
    p.drawRect(rect);

    // draw inner rect
    QColor c = Utils::StyleHelper::panelTextColor();
    c.setAlpha(180);
    p.setPen(Qt::NoPen);

    QRect inner = rect.adjusted(2, 2, -1, -1);
    inner.adjust(0, 0, qRound((percent - 1) * inner.width()), 0);
    if (m_error) {
        QColor red(255, 60, 0, 210);
        c = red;
        // avoid too small red bar
        if (inner.width() < 10)
            inner.adjust(0, 0, 10 - inner.width(), 0);
    } else if (value() == maximum()) {
        c = QColor(120, 245, 90, 180);
    }

    QLinearGradient grad(inner.topLeft(), inner.bottomLeft());
    grad.setColorAt(0, c.lighter(114));
    grad.setColorAt(0.5, c.lighter(104));
    grad.setColorAt(0.51, c.darker(108));
    grad.setColorAt(1, c.darker(120));

    p.setBrush(grad);
    p.drawRect(inner);

    if (value() < maximum() && !m_error) {
        QColor cancelOutline = Utils::StyleHelper::panelTextColor();
        p.setPen(cancelOutline);
        QRect cancelRect(rect.right() - m_progressHeight + 2, rect.top(), m_progressHeight-1, rect.height());
        if (cancelRect.contains(mapFromGlobal(QCursor::pos())))
            p.setBrush(QColor(230, 90, 40, 190));
        else
            p.setBrush(Qt::NoBrush);

        p.drawRect(cancelRect);

        p.setPen(QPen(QColor(0, 0, 0, 70), 3));
        p.drawLine(cancelRect.center()+QPoint(-1,-1), cancelRect.center()+QPoint(+3,+3));
        p.drawLine(cancelRect.center()+QPoint(+3,-1), cancelRect.center()+QPoint(-1,+3));

        p.setPen(Utils::StyleHelper::panelTextColor());
        p.drawLine(cancelRect.center()+QPoint(-1,-1), cancelRect.center()+QPoint(+3,+3));
        p.drawLine(cancelRect.center()+QPoint(+3,-1), cancelRect.center()+QPoint(-1,+3));
    }
}
Example #2
0
void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
{
    if (!validIndex(tabIndex)) {
        qWarning("invalid index");
        return;
    }
    painter->save();

    QRect rect = tabRect(tabIndex);
    bool selected = (tabIndex == m_currentIndex);
    bool enabled = isTabEnabled(tabIndex);

    if (selected) {
        //background
        painter->save();
        QLinearGradient grad(rect.topLeft(), rect.topRight());
        grad.setColorAt(0, QColor(255, 255, 255, 140));
        grad.setColorAt(1, QColor(255, 255, 255, 210));
        painter->fillRect(rect.adjusted(0, 0, 0, -1), grad);
        painter->restore();

        //shadows
        painter->setPen(QColor(0, 0, 0, 110));
        painter->drawLine(rect.topLeft() + QPoint(1,-1), rect.topRight() - QPoint(0,1));
        painter->drawLine(rect.bottomLeft(), rect.bottomRight());
        painter->setPen(QColor(0, 0, 0, 40));
        painter->drawLine(rect.topLeft(), rect.bottomLeft());

        //highlights
        painter->setPen(QColor(255, 255, 255, 50));
        painter->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0,2));
        painter->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0,1));
        painter->setPen(QColor(255, 255, 255, 40));
        painter->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight());
        painter->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1));
        painter->drawLine(rect.bottomLeft() + QPoint(0,-1), rect.bottomRight()-QPoint(0,1));
    }

    QString tabText(this->tabText(tabIndex));
    QRect tabTextRect(rect);
    const bool drawIcon = rect.height() > 36;
    QRect tabIconRect(tabTextRect);
    tabTextRect.translate(0, drawIcon ? -2 : 1);
    QFont boldFont(painter->font());
    boldFont.setPointSizeF(StyleHelper::sidebarFontSize());
    boldFont.setBold(true);
    painter->setFont(boldFont);
    painter->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
    const int textFlags = Qt::AlignCenter | (drawIcon ? Qt::AlignBottom : Qt::AlignVCenter) | Qt::TextWordWrap;
    if (enabled) {
        painter->drawText(tabTextRect, textFlags, tabText);
        painter->setPen(selected ? QColor(60, 60, 60) : StyleHelper::panelTextColor());
    } else {
        painter->setPen(selected ? StyleHelper::panelTextColor() : QColor(255, 255, 255, 120));
    }
    if (/*!Utils::HostOsInfo::isMacHost()*/ true && !selected && enabled) {
        painter->save();
        int fader = int(m_tabs[tabIndex]->fader());
        QLinearGradient grad(rect.topLeft(), rect.topRight());
        grad.setColorAt(0, Qt::transparent);
        grad.setColorAt(0.5, QColor(255, 255, 255, fader));
        grad.setColorAt(1, Qt::transparent);
        painter->fillRect(rect, grad);
        painter->setPen(QPen(grad, 1.0));
        painter->drawLine(rect.topLeft(), rect.topRight());
        painter->drawLine(rect.bottomLeft(), rect.bottomRight());
        painter->restore();
    }

    if (!enabled)
        painter->setOpacity(0.7);

    if (drawIcon) {
        int textHeight = painter->fontMetrics().boundingRect(QRect(0, 0, width(), height()), Qt::TextWordWrap, tabText).height();
        tabIconRect.adjust(0, 4, 0, -textHeight);
        StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, painter, enabled ? QIcon::Normal : QIcon::Disabled);
    }

    painter->translate(0, -1);
    painter->drawText(tabTextRect, textFlags, tabText);
    painter->restore();
}
Example #3
0
PreconditionerBlockMS<space_type>::PreconditionerBlockMS(space_ptrtype Xh,             // (u)x(p)
                                                         ModelProperties model,        // model
                                                         std::string const& p,         // prefix
                                                         sparse_matrix_ptrtype AA )    // The matrix
    :
        M_backend(backend()),           // the backend associated to the PC
        M_Xh( Xh ),
        M_Vh( Xh->template functionSpace<0>() ), // Potential
        M_Qh( Xh->template functionSpace<1>() ), // Lagrange
        M_Vh_indices( M_Vh->nLocalDofWithGhost() ),
        M_Qh_indices( M_Qh->nLocalDofWithGhost() ),
        M_uin( M_backend->newVector( M_Vh )  ),
        M_uout( M_backend->newVector( M_Vh )  ),
        M_pin( M_backend->newVector( M_Qh )  ),
        M_pout( M_backend->newVector( M_Qh )  ),
        U( M_Xh, "U" ),
        M_mass(M_backend->newMatrix(M_Vh,M_Vh)),
        M_L(M_backend->newMatrix(M_Qh,M_Qh)),
        M_er( 1. ),
        M_model( model ),
        M_prefix( p ),
        M_prefix_11( p+".11" ),
        M_prefix_22( p+".22" ),
        u(M_Vh, "u"),
        ozz(M_Vh, "ozz"),
        zoz(M_Vh, "zoz"),
        zzo(M_Vh, "zzo"),
        M_ozz(M_backend->newVector( M_Vh )),
        M_zoz(M_backend->newVector( M_Vh )),
        M_zzo(M_backend->newVector( M_Vh )),
        X(M_Qh, "X"),
        Y(M_Qh, "Y"),
        Z(M_Qh, "Z"),
        M_X(M_backend->newVector( M_Qh )),
        M_Y(M_backend->newVector( M_Qh )),
        M_Z(M_backend->newVector( M_Qh )),
        phi(M_Qh, "phi")
{
    tic();
    LOG(INFO) << "[PreconditionerBlockMS] setup starts";
    this->setMatrix( AA );
    this->setName(M_prefix);

    /* Indices are need to extract sub matrix */
    std::iota( M_Vh_indices.begin(), M_Vh_indices.end(), 0 );
    std::iota( M_Qh_indices.begin(), M_Qh_indices.end(), M_Vh->nLocalDofWithGhost() );

    M_11 = AA->createSubMatrix( M_Vh_indices, M_Vh_indices, true, true);

    /* Boundary conditions */
    BoundaryConditions M_bc = M_model.boundaryConditions();
    map_vector_field<FEELPP_DIM,1,2> m_dirichlet_u { M_bc.getVectorFields<FEELPP_DIM> ( "u", "Dirichlet" ) };
    map_scalar_field<2> m_dirichlet_p { M_bc.getScalarFields<2> ( "phi", "Dirichlet" ) };

    /* Compute the mass matrix (needed in first block, constant) */
    auto f2A = form2(_test=M_Vh, _trial=M_Vh, _matrix=M_mass);
    auto f1A = form1(_test=M_Vh);
    f2A = integrate(_range=elements(M_Vh->mesh()), _expr=inner(idt(u),id(u))); // M
    for(auto const & it : m_dirichlet_u )
    {
        LOG(INFO) << "Applying " << it.second << " on " << it.first << " for "<<M_prefix_11<<"\n";
        f2A += on(_range=markedfaces(M_Vh->mesh(),it.first), _expr=it.second,_rhs=f1A, _element=u, _type="elimination_symmetric");
    }
    
    /* Compute the L (= er * grad grad) matrix (the second block) */
    auto f2L = form2(_test=M_Qh,_trial=M_Qh, _matrix=M_L);
    for(auto it : M_model.materials() )
    { 
        f2L += integrate(_range=markedelements(M_Qh->mesh(),marker(it)), _expr=M_er*inner(gradt(phi), grad(phi)));
    }
    auto f1LQ = form1(_test=M_Qh);

    for(auto const & it : m_dirichlet_p)
    {
        LOG(INFO) << "Applying " << it.second << " on " << it.first << " for "<<M_prefix_22<<"\n";
        f2L += on(_range=markedfaces(M_Qh->mesh(),it.first),_element=phi, _expr=it.second, _rhs=f1LQ, _type="elimination_symmetric");
    }


    if(soption(_name="pc-type", _prefix=M_prefix_11) == "ams")
#if FEELPP_DIM == 3
    {
        M_grad  = Grad( _domainSpace=M_Qh, _imageSpace=M_Vh);

        // This preconditioner is linked to that backend : the backend will
        // automatically use the preconditioner.
        auto prec = preconditioner(_pc=pcTypeConvertStrToEnum(soption(M_prefix_11+".pc-type")),
                                   _backend=backend(_name=M_prefix_11),
                                   _prefix=M_prefix_11,
                                   _matrix=M_11
                                  );
        prec->setMatrix(M_11);
        prec->attachAuxiliarySparseMatrix("G",M_grad.matPtr());
        if(boption(M_prefix_11+".useEdge"))
        {
            LOG(INFO) << "[ AMS ] : using SetConstantEdgeVector \n";
            ozz.on(_range=elements(M_Vh->mesh()),_expr=vec(cst(1),cst(0),cst(0)));
            zoz.on(_range=elements(M_Vh->mesh()),_expr=vec(cst(0),cst(1),cst(0)));
            zzo.on(_range=elements(M_Vh->mesh()),_expr=vec(cst(0),cst(0),cst(1)));
            *M_ozz = ozz; M_ozz->close();
            *M_zoz = zoz; M_zoz->close();
            *M_zzo = zzo; M_zzo->close();

            prec->attachAuxiliaryVector("Px",M_ozz);
            prec->attachAuxiliaryVector("Py",M_zoz);
            prec->attachAuxiliaryVector("Pz",M_zzo);
        }
        else
        {
            LOG(INFO) << "[ AMS ] : using SetCoordinates \n";
            X.on(_range=elements(M_Vh->mesh()),_expr=Px());
            Y.on(_range=elements(M_Vh->mesh()),_expr=Py());
            Z.on(_range=elements(M_Vh->mesh()),_expr=Pz());
            *M_X = X; M_X->close();
            *M_Y = Y; M_Y->close();
            *M_Z = Z; M_Z->close();
            prec->attachAuxiliaryVector("X",M_X);
            prec->attachAuxiliaryVector("Y",M_Y);
            prec->attachAuxiliaryVector("Z",M_Z);
        }
    }
#else
    std::cerr << "ams preconditioner is not interfaced in two dimensions\n";
#endif
    toc( "[PreconditionerBlockMS] setup done ", FLAGS_v > 0 );
}
	void paintContact(QPainter* mp, const QStyleOptionViewItem& option, const QModelIndex& index, GCUserViewItem* item) const
	{
		mp->save();
		QStyleOptionViewItem o = option;
		QPalette palette = o.palette;
		MUCItem::Role r = item->s.mucItem().role();
		QRect rect = o.rect;

		if(nickColoring_) {
			if(r == MUCItem::Moderator)
				palette.setColor(QPalette::Text, colorModerator_);
			else if(r == MUCItem::Participant)
				palette.setColor(QPalette::Text, colorParticipant_);
			else if(r == MUCItem::Visitor)
				palette.setColor(QPalette::Text, colorVisitor_);
			else
				palette.setColor(QPalette::Text, colorNoRole_);
		}

		mp->fillRect(rect, (o.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base));

		if(showAvatar_) {
			QPixmap ava = item->avatar();
			if(ava.isNull()) {
				ava = IconsetFactory::iconPixmap("psi/default_avatar");
			}
			ava = AvatarFactory::roundedAvatar(ava, avatarRadius_, avatarSize_);
			QRect avaRect(rect);
			avaRect.setWidth(ava.width());
			avaRect.setHeight(ava.height());
			if(!avatarAtLeft_) {
				avaRect.moveTopRight(rect.topRight());
				avaRect.translate(-1, 1);
				rect.setRight(avaRect.left() - 1);
			}
			else {
				avaRect.translate(1, 1);
				rect.setLeft(avaRect.right() + 1);
			}
			mp->drawPixmap(avaRect, ava);
		}

		QPixmap status = showStatusIcons_ ? item->icon() : QPixmap();
		int h = rect.height();
		int sh = status.isNull() ? 0 : status.height();
		rect.setHeight(qMax(sh, fontHeight_));
		rect.moveTop(rect.top() + (h - rect.height())/2);
		if(!status.isNull()) {
			QRect statusRect(rect);
			statusRect.setWidth(status.width());
			statusRect.setHeight(status.height());
			statusRect.translate(1, 1);
			mp->drawPixmap(statusRect, status);
			rect.setLeft(statusRect.right() + 2);
		}
		else
			rect.setLeft(rect.left() + 2);

		mp->setPen(QPen((o.state & QStyle::State_Selected) ? palette.color(QPalette::HighlightedText) : palette.color(QPalette::Text)));
		mp->setFont(o.font);
		mp->setClipRect(rect);
		QTextOption to;
		to.setWrapMode(QTextOption::NoWrap);
		mp->drawText(rect, index.data(Qt::DisplayRole).toString(), to);

		QList<QPixmap> rightPixs;
		if(showClients_) {
			GCUserView *gcuv = (GCUserView*)item->treeWidget();
			GCMainDlg* dlg = gcuv->mainDlg();
			QPixmap clientPix;
			if(dlg) {
				UserListItem u;
				const QString &nick = item->text(0);
				Jid caps_jid(/*s.mucItem().jid().isEmpty() ? */ dlg->jid().withResource(nick) /* : s.mucItem().jid()*/);
				CapsManager *cm = dlg->account()->client()->capsManager();
				QString client_name = cm->clientName(caps_jid);
				QString client_version = (client_name.isEmpty() ? QString() : cm->clientVersion(caps_jid));
				UserResource ur;
				ur.setStatus(item->s);
				ur.setClient(client_name,client_version,"");
				u.userResourceList().append(ur);
				QStringList clients = u.clients();
				if(!clients.isEmpty())
					clientPix = IconsetFactory::iconPixmap("clients/" + clients.takeFirst());
			}
			if(!clientPix.isNull())
				rightPixs.push_back(clientPix);
		}

		if(showAffiliations_) {
			MUCItem::Affiliation a = item->s.mucItem().affiliation();
			QPixmap pix;
			if(a == MUCItem::Owner)
				pix = IconsetFactory::iconPixmap("affiliation/owner");
			else if(a == MUCItem::Admin)
				pix = IconsetFactory::iconPixmap("affiliation/admin");
			else if(a == MUCItem::Member)
				pix = IconsetFactory::iconPixmap("affiliation/member");
			else if(a == MUCItem::Outcast)
				pix = IconsetFactory::iconPixmap("affiliation/outcast");
			else
				pix = IconsetFactory::iconPixmap("affiliation/noaffiliation");
			if(!pix.isNull())
				rightPixs.push_back(pix);
		}

		mp->restore();

		if(rightPixs.isEmpty())
			return;

		int sumWidth = 0;
		foreach (const QPixmap& pix, rightPixs) {
				sumWidth += pix.width();
		}
		sumWidth += rightPixs.count();

		QColor bgc = (option.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base);
		QColor tbgc = bgc;
		tbgc.setAlpha(0);
		QLinearGradient grad(rect.right() - sumWidth - 20, 0, rect.right() - sumWidth, 0);
		grad.setColorAt(0, tbgc);
		grad.setColorAt(1, bgc);
		QBrush tbakBr(grad);
		QRect gradRect(rect);
		gradRect.setLeft(gradRect.right() - sumWidth - 20);
		mp->fillRect(gradRect, tbakBr);

		QRect iconRect(rect);
		for (int i=0; i<rightPixs.size(); i++) {
			const QPixmap pix = rightPixs[i];
			iconRect.setRight(iconRect.right() - pix.width() -1);
			mp->drawPixmap(iconRect.topRight(), pix);
		}

	}
Example #5
0
void caLinearGauge::drawColorBar(QPainter *p)
{
    if (m_colorMode == GRADIENT)
    {
        QPoint start, stop;
        QRect r;
        if (m_orientation == Qt::Horizontal)
        {
            start = QPoint(0,0);
            stop = QPoint(100,0);
            r = QRect(0, scalePos, 100, barSize);
        }
        else
        {
            start = QPoint(0,100);
            stop = QPoint(0,0);
            r = QRect(0, 0, barSize, 100);
        }
        QLinearGradient	grad(start, stop);
        for (int i = 0; i < v_p.size(); i++) {
            grad.setColorAt(v_p[i], v_c[i]);
    }
        p->setBrush(grad);
        p->drawRect(r);
    }
    else if (m_colorMode == COLORBAR)
    {
        p->setPen(Qt::NoPen);
        if (m_orientation == Qt::Horizontal)
        {
            QVector<qreal> widths;
            foreach(qreal w, v_p)
                widths << w * 100;
            for (int i = 1; i < v_p.size(); i++)
            {
                p->setBrush(v_c[i]);
                p->drawRect(QRectF(widths[i-1], scalePos, widths[i]-widths[i-1], barSize));
            }
            p->setBrush(Qt::NoBrush);
            p->setPen(Qt::black);
            p->drawRect(0, scalePos, 100, barSize);
        }
        else
        {
            QVector<qreal> heights;
            foreach(qreal h, v_p)
                heights << 100*(1-h);
            for (int i = 1; i < v_p.size(); i++)
            {
                p->setBrush(v_c[i]);
                p->drawRect(QRectF(0, heights[i], barSize, heights[i-1]-heights[i]));
            }
            p->setBrush(Qt::NoBrush);
            p->setPen(Qt::black);
            p->drawRect(0, 0, barSize, 100);
        }
    }
    else if (m_colorMode == SINGLECOLOR)
    {
        p->setBrush(v_c[0]);
        if (m_orientation == Qt::Horizontal)
            p->drawRect(0, scalePos, 100, barSize);
        else
            p->drawRect(0, 0, barSize, 100);
    }

    if (m_fillMode != ALL)
    {
        double v1, v2, min = 0.0, max = 0.0;
        v1 = (m_value-m_minValue)/(m_maxValue-m_minValue);

        p->setPen(Qt::black);
        p->setBrush(palette().background());
        if (m_fillMode == FROM_MIN)
        {
            max = v1;
            min = 0.0;
        }
        else if (m_fillMode == FROM_ZERO)
        {
            v2  = (-m_minValue)/(m_maxValue-m_minValue);
            min = qMin(v1, v2);
            max = qMax(v1, v2);
        }
        else if (m_fillMode == FROM_REF)
        {
            v2  = (m_reference-m_minValue)/(m_maxValue-m_minValue);
            min = qMin(v1, v2);
            max = qMax(v1, v2);
        }

        if (m_orientation == Qt::Horizontal)
        {
            p->drawRect(QRectF(0, scalePos, 100.0*min, barSize));
            p->drawRect(QRectF(100.0*max, scalePos, 100.0*(1-max), barSize));
        }
        else
        {
            p->drawRect(QRectF(0.0, 100*(1-min), barSize, 100*min));
            p->drawRect(QRectF(0.0, 0.0, barSize, 100.0*(1-max)));
        }
    }
}
Example #6
0
// 4D simplex noise
float noise(float x, float y, float z, float w) {
  
  // The skewing and unskewing factors are hairy again for the 4D case
#define F4 0.309016994 // F4 = (Math.sqrt(5.0)-1.0)/4.0
#define G4 0.138196601 // G4 = (5.0-Math.sqrt(5.0))/20.0

    float n0, n1, n2, n3, n4; // Noise contributions from the five corners

    // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
    float s = (x + y + z + w) * F4; // Factor for 4D skewing
    float xs = x + s;
    float ys = y + s;
    float zs = z + s;
    float ws = w + s;
    int i = FASTFLOOR(xs);
    int j = FASTFLOOR(ys);
    int k = FASTFLOOR(zs);
    int l = FASTFLOOR(ws);

    float t = (i + j + k + l) * G4; // Factor for 4D unskewing
    float X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
    float Y0 = j - t;
    float Z0 = k - t;
    float W0 = l - t;

    float x0 = x - X0;  // The x,y,z,w distances from the cell origin
    float y0 = y - Y0;
    float z0 = z - Z0;
    float w0 = w - W0;

    // For the 4D case, the simplex is a 4D shape I won't even try to describe.
    // To find out which of the 24 possible simplices we're in, we need to
    // determine the magnitude ordering of x0, y0, z0 and w0.
    // The method below is a good way of finding the ordering of x,y,z,w and
    // then find the correct traversal order for the simplex we’re in.
    // First, six pair-wise comparisons are performed between each possible pair
    // of the four coordinates, and the results are used to add up binary bits
    // for an integer index.
    int c1 = (x0 > y0) ? 32 : 0;
    int c2 = (x0 > z0) ? 16 : 0;
    int c3 = (y0 > z0) ? 8 : 0;
    int c4 = (x0 > w0) ? 4 : 0;
    int c5 = (y0 > w0) ? 2 : 0;
    int c6 = (z0 > w0) ? 1 : 0;
    int c = c1 + c2 + c3 + c4 + c5 + c6;

    int i1, j1, k1, l1; // The integer offsets for the second simplex corner
    int i2, j2, k2, l2; // The integer offsets for the third simplex corner
    int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner

    // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
    // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w
    // impossible. Only the 24 indices which have non-zero entries make any sense.
    // We use a thresholding to set the coordinates in turn from the largest magnitude.
    // The number 3 in the "simplex" array is at the position of the largest coordinate.
    i1 = simplex[c][0]>=3 ? 1 : 0;
    j1 = simplex[c][1]>=3 ? 1 : 0;
    k1 = simplex[c][2]>=3 ? 1 : 0;
    l1 = simplex[c][3]>=3 ? 1 : 0;
    // The number 2 in the "simplex" array is at the second largest coordinate.
    i2 = simplex[c][0]>=2 ? 1 : 0;
    j2 = simplex[c][1]>=2 ? 1 : 0;
    k2 = simplex[c][2]>=2 ? 1 : 0;
    l2 = simplex[c][3]>=2 ? 1 : 0;
    // The number 1 in the "simplex" array is at the second smallest coordinate.
    i3 = simplex[c][0]>=1 ? 1 : 0;
    j3 = simplex[c][1]>=1 ? 1 : 0;
    k3 = simplex[c][2]>=1 ? 1 : 0;
    l3 = simplex[c][3]>=1 ? 1 : 0;
    // The fifth corner has all coordinate offsets = 1, so no need to look that up.

    float x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords
    float y1 = y0 - j1 + G4;
    float z1 = z0 - k1 + G4;
    float w1 = w0 - l1 + G4;
    float x2 = x0 - i2 + 2.0f*G4; // Offsets for third corner in (x,y,z,w) coords
    float y2 = y0 - j2 + 2.0f*G4;
    float z2 = z0 - k2 + 2.0f*G4;
    float w2 = w0 - l2 + 2.0f*G4;
    float x3 = x0 - i3 + 3.0f*G4; // Offsets for fourth corner in (x,y,z,w) coords
    float y3 = y0 - j3 + 3.0f*G4;
    float z3 = z0 - k3 + 3.0f*G4;
    float w3 = w0 - l3 + 3.0f*G4;
    float x4 = x0 - 1.0f + 4.0f*G4; // Offsets for last corner in (x,y,z,w) coords
    float y4 = y0 - 1.0f + 4.0f*G4;
    float z4 = z0 - 1.0f + 4.0f*G4;
    float w4 = w0 - 1.0f + 4.0f*G4;

    // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds
    int ii = i & 0xff;
    int jj = j & 0xff;
    int kk = k & 0xff;
    int ll = l & 0xff;

    // Calculate the contribution from the five corners
    float t0 = 0.6f - x0*x0 - y0*y0 - z0*z0 - w0*w0;
    if(t0 < 0.0f) n0 = 0.0f;
    else {
      t0 *= t0;
      n0 = t0 * t0 * grad(perm[ii+perm[jj+perm[kk+perm[ll]]]], x0, y0, z0, w0);
    }

   float t1 = 0.6f - x1*x1 - y1*y1 - z1*z1 - w1*w1;
    if(t1 < 0.0f) n1 = 0.0f;
    else {
      t1 *= t1;
      n1 = t1 * t1 * grad(perm[ii+i1+perm[jj+j1+perm[kk+k1+perm[ll+l1]]]], x1, y1, z1, w1);
    }

   float t2 = 0.6f - x2*x2 - y2*y2 - z2*z2 - w2*w2;
    if(t2 < 0.0f) n2 = 0.0f;
    else {
      t2 *= t2;
      n2 = t2 * t2 * grad(perm[ii+i2+perm[jj+j2+perm[kk+k2+perm[ll+l2]]]], x2, y2, z2, w2);
    }

   float t3 = 0.6f - x3*x3 - y3*y3 - z3*z3 - w3*w3;
    if(t3 < 0.0f) n3 = 0.0f;
    else {
      t3 *= t3;
      n3 = t3 * t3 * grad(perm[ii+i3+perm[jj+j3+perm[kk+k3+perm[ll+l3]]]], x3, y3, z3, w3);
    }

   float t4 = 0.6f - x4*x4 - y4*y4 - z4*z4 - w4*w4;
    if(t4 < 0.0f) n4 = 0.0f;
    else {
      t4 *= t4;
      n4 = t4 * t4 * grad(perm[ii+1+perm[jj+1+perm[kk+1+perm[ll+1]]]], x4, y4, z4, w4);
    }

    // Sum up and scale the result to cover the range [-1,1]
    return 27.0f * (n0 + n1 + n2 + n3 + n4); // TODO: The scale factor is preliminary!
  }
    void ShimmerWidget::paintEvent(QPaintEvent * event)
    {

        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setOpacity(0.4);
        painter.setPen(Qt::NoPen);
        QSize size = this->_svgRenderer.defaultSize();
        size.scale(150, 150, Qt::KeepAspectRatio);
        QRect sRect(QPoint(0, 0), size);
        sRect.moveCenter(this->rect().center());
        QPixmap overlay(sRect.size());
        overlay.fill(QColor(0, 0, 0, 0));
        QPainter overlayPainter(&overlay);
        this->_svgRenderer.render(&overlayPainter, QRect(QPoint(0, 0), sRect.size()));
        qreal offset = this->_shimmer.isValid() ? (this->_shimmer.elapsed() / 1000.0) : -1.0;

        if (this->_rippleOn)
        {
            float opacity = (sin(this->_ripple.elapsed()/800.0) + 1) / 2.0;

            overlayPainter.setBrush(QColor(255,255,255,opacity * 128));
            overlayPainter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
            overlayPainter.drawRect(overlay.rect());
            QTimer::singleShot(80, this, SLOT(update()));
        }
        else
        {
            if (offset > 5.0)
            {
                this->_shimmer.restart();
                QTimer::singleShot(40, this, SLOT(update()));
            }
            else if (offset > 1.0)
            {
                QTimer::singleShot(90000, this, SLOT(update()));
            }
            else if (offset >= 0.0)
            {
                QLinearGradient grad(QPointF(-0.5 * sRect.width(), 500), QPointF(sRect.width() * 1.5, 0));
                grad.setColorAt(qBound(0.0, offset, 1.0), QColor(0, 0, 0));
                grad.setColorAt(qBound(0.0, offset + 0.05, 1.0), QColor(200, 230, 255));
                grad.setColorAt(qBound(0.0, offset + 0.1, 1.0), QColor(0, 0, 0));
                overlayPainter.setBrush(grad);
                overlayPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
                overlayPainter.drawRect(QRect(QPoint(0, 0), sRect.size()));

                QTimer::singleShot(40, this, SLOT(update()));
            }

            if (this->_pulse.isValid() && this->_pulse.elapsed() < 300)
            {
                //              float opacity = cos((this->_pulse.elapsed()/500.0) * (3.141 / 2.0));
                float opacity = 1.0 - (this->_pulse.elapsed()/300.0);

                //              qDebug() << "opacity = " << opacity;
                overlayPainter.setBrush(QColor(255,0,0,opacity * 255));
                overlayPainter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
                overlayPainter.drawRect(overlay.rect());
                QTimer::singleShot(40, this, SLOT(update()));
            }
        }
        painter.drawPixmap(sRect.topLeft(), overlay);
    }
Example #8
0
// 3D simplex noise
float noise(float x, float y, float z) {

// Simple skewing factors for the 3D case
#define F3 0.333333333
#define G3 0.166666667

    float n0, n1, n2, n3; // Noise contributions from the four corners

    // Skew the input space to determine which simplex cell we're in
    float s = (x+y+z)*F3; // Very nice and simple skew factor for 3D
    float xs = x+s;
    float ys = y+s;
    float zs = z+s;
    int i = FASTFLOOR(xs);
    int j = FASTFLOOR(ys);
    int k = FASTFLOOR(zs);

    float t = (float)(i+j+k)*G3; 
    float X0 = i-t; // Unskew the cell origin back to (x,y,z) space
    float Y0 = j-t;
    float Z0 = k-t;
    float x0 = x-X0; // The x,y,z distances from the cell origin
    float y0 = y-Y0;
    float z0 = z-Z0;

    // For the 3D case, the simplex shape is a slightly irregular tetrahedron.
    // Determine which simplex we are in.
    int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords
    int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords

/* This code would benefit from a backport from the GLSL version! */
    if(x0>=y0) {
      if(y0>=z0)
        { i1=1; j1=0; k1=0; i2=1; j2=1; k2=0; } // X Y Z order
        else if(x0>=z0) { i1=1; j1=0; k1=0; i2=1; j2=0; k2=1; } // X Z Y order
        else { i1=0; j1=0; k1=1; i2=1; j2=0; k2=1; } // Z X Y order
      }
    else { // x0<y0
      if(y0<z0) { i1=0; j1=0; k1=1; i2=0; j2=1; k2=1; } // Z Y X order
      else if(x0<z0) { i1=0; j1=1; k1=0; i2=0; j2=1; k2=1; } // Y Z X order
      else { i1=0; j1=1; k1=0; i2=1; j2=1; k2=0; } // Y X Z order
    }

    // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
    // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and
    // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where
    // c = 1/6.

    float x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords
    float y1 = y0 - j1 + G3;
    float z1 = z0 - k1 + G3;
    float x2 = x0 - i2 + 2.0f*G3; // Offsets for third corner in (x,y,z) coords
    float y2 = y0 - j2 + 2.0f*G3;
    float z2 = z0 - k2 + 2.0f*G3;
    float x3 = x0 - 1.0f + 3.0f*G3; // Offsets for last corner in (x,y,z) coords
    float y3 = y0 - 1.0f + 3.0f*G3;
    float z3 = z0 - 1.0f + 3.0f*G3;

    // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds
    int ii = i & 0xff;
    int jj = j & 0xff;
    int kk = k & 0xff;

    // Calculate the contribution from the four corners
    float t0 = 0.6f - x0*x0 - y0*y0 - z0*z0;
    if(t0 < 0.0f) n0 = 0.0f;
    else {
      t0 *= t0;
      n0 = t0 * t0 * grad(perm[ii+perm[jj+perm[kk]]], x0, y0, z0);
    }

    float t1 = 0.6f - x1*x1 - y1*y1 - z1*z1;
    if(t1 < 0.0f) n1 = 0.0f;
    else {
      t1 *= t1;
      n1 = t1 * t1 * grad(perm[ii+i1+perm[jj+j1+perm[kk+k1]]], x1, y1, z1);
    }

    float t2 = 0.6f - x2*x2 - y2*y2 - z2*z2;
    if(t2 < 0.0f) n2 = 0.0f;
    else {
      t2 *= t2;
      n2 = t2 * t2 * grad(perm[ii+i2+perm[jj+j2+perm[kk+k2]]], x2, y2, z2);
    }

    float t3 = 0.6f - x3*x3 - y3*y3 - z3*z3;
    if(t3<0.0f) n3 = 0.0f;
    else {
      t3 *= t3;
      n3 = t3 * t3 * grad(perm[ii+1+perm[jj+1+perm[kk+1]]], x3, y3, z3);
    }

    // Add contributions from each corner to get the final noise value.
    // The result is scaled to stay just inside [-1,1]
    return 32.0f * (n0 + n1 + n2 + n3); // TODO: The scale factor is preliminary!
  }
Example #9
0
// 2D simplex noise
float noise(float x, float y) {

#define F2 0.366025403 // F2 = 0.5*(sqrt(3.0)-1.0)
#define G2 0.211324865 // G2 = (3.0-Math.sqrt(3.0))/6.0

    float n0, n1, n2; // Noise contributions from the three corners

    // Skew the input space to determine which simplex cell we're in
    float s = (x+y)*F2; // Hairy factor for 2D
    float xs = x + s;
    float ys = y + s;
    int i = FASTFLOOR(xs);
    int j = FASTFLOOR(ys);

    float t = (float)(i+j)*G2;
    float X0 = i-t; // Unskew the cell origin back to (x,y) space
    float Y0 = j-t;
    float x0 = x-X0; // The x,y distances from the cell origin
    float y0 = y-Y0;

    // For the 2D case, the simplex shape is an equilateral triangle.
    // Determine which simplex we are in.
    int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
    if(x0>y0) {i1=1; j1=0;} // lower triangle, XY order: (0,0)->(1,0)->(1,1)
    else {i1=0; j1=1;}      // upper triangle, YX order: (0,0)->(0,1)->(1,1)

    // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
    // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
    // c = (3-sqrt(3))/6

    float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
    float y1 = y0 - j1 + G2;
    float x2 = x0 - 1.0f + 2.0f * G2; // Offsets for last corner in (x,y) unskewed coords
    float y2 = y0 - 1.0f + 2.0f * G2;

    // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds
    int ii = i & 0xff;
    int jj = j & 0xff;

    // Calculate the contribution from the three corners
    float t0 = 0.5f - x0*x0-y0*y0;
    if(t0 < 0.0f) n0 = 0.0f;
    else {
      t0 *= t0;
      n0 = t0 * t0 * grad(perm[ii+perm[jj]], x0, y0); 
    }

    float t1 = 0.5f - x1*x1-y1*y1;
    if(t1 < 0.0f) n1 = 0.0f;
    else {
      t1 *= t1;
      n1 = t1 * t1 * grad(perm[ii+i1+perm[jj+j1]], x1, y1);
    }

    float t2 = 0.5f - x2*x2-y2*y2;
    if(t2 < 0.0f) n2 = 0.0f;
    else {
      t2 *= t2;
      n2 = t2 * t2 * grad(perm[ii+1+perm[jj+1]], x2, y2);
    }

    // Add contributions from each corner to get the final noise value.
    // The result is scaled to return values in the interval [-1,1].
    return 40.0f * (n0 + n1 + n2); // TODO: The scale factor is preliminary!
  }
Example #10
0
double *fmin_cg(double *x,
                int n,

                double (*val) (double *, int, void *),
                void (*grad) (double *, double *, int, void *),
                double (*valgrad) (double *, double *, int, void *),

                double tol,
                void *instance,

                fmin_cg_args_t *args,
                fmin_cg_stats_t *stats,
                double *work_array) {

    void *preallocated = work_array;
    double *d, *xtemp, *g, *gtemp;
    double beta;
    double yk, tmp, dnorm, gnorm;
    int max_iterations, i;
    fmin_vars_t vars = {val, grad, valgrad, x, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, n, instance, 0, 0, 0};

    work_array = preallocated ? work_array : calloc(4*n, sizeof *work_array);
    args = args ? args : &fmin_cg_default_args;

    max_iterations = args->max_iterations == -1 ? 200*n : args->max_iterations;

    d = work_array;
    xtemp = work_array + n;
    g = work_array + 2*n;
    gtemp = work_array + 3*n;

    grad(g, x, n, instance);
    vars.ngrad++;
    gnorm = 0;
    for (i = 0; i < n; i++) {
        d[i] = -g[i];
        gnorm += g[i]*g[i];
    }

    vars.x = x;
    vars.xtemp = xtemp;
    vars.d = d;
    vars.g = g;
    vars.gtemp = gtemp;

    for (vars.niterations = 0; gnorm > tol && vars.niterations < max_iterations; vars.niterations++) {
        vars.f0 = val(x, n, instance);
        vars.nval++;
        vars.old_fa = vars.f0 + 5000;
        vars.g0 = 0;
        for (i = 0; i < n; i++) {
            vars.g0 += g[i]*d[i];
        }

        args->linesearch(&vars, NULL);
        for (i = 0; i < vars.n; i++) {
            x[i] = xtemp[i];
        }

        if (vars.ga == FMIN_LINESEARCH_FAIL) {
            for (i = 0; i < vars.n; i++) {
                gtemp[i] = g[i];
            }
        }

        beta = 0;
        tmp = 0;
        switch (args->cg_type) {
            case FMIN_CG_HS: {
                for (i = 0; i < n; i++) {
                    yk = gtemp[i] - g[i];
                    beta += gtemp[i] * yk;
                    tmp += d[i]*yk;
                }
                beta /= tmp;
                break;
            }

            case FMIN_CG_FR: {
                for (i = 0; i < n; i++) {
                    beta += gtemp[i]*gtemp[i];
                    tmp += g[i]*g[i];
                }
                beta /= tmp;
                break;
            }

            case FMIN_CG_PRP: {
                for (i = 0; i < n; i++) {
                    beta += gtemp[i]*(gtemp[i] - g[i]);
                    tmp += g[i]*g[i];
                }
                beta /= tmp;
                break;
            }

            case FMIN_CG_CD: {
                for (i = 0; i < n; i++) {
                    beta += gtemp[i]*gtemp[i];
                    tmp += -d[i]*g[i];
                }
                beta /= tmp;
                break;
            }

            case FMIN_CG_LS: {
                for (i = 0; i < n; i++) {
                    beta += gtemp[i]*(gtemp[i]-g[i]);
                    tmp += -d[i]*g[i];
                }
                beta /= tmp;
                break;
            }

            case FMIN_CG_DY: {
                for (i = 0; i < n; i++) {
                    beta += gtemp[i]*gtemp[i];
                    tmp += d[i]*(gtemp[i]-g[i]);
                }
                beta /= tmp;
                break;
            }

            case FMIN_CG_N: {
                double dkyk = 0;
                tmp = 0;
                for (i = 0; i < n; i++) {
                    yk = (gtemp[i]-g[i]);
                    dkyk += d[i]*yk;
                    tmp += yk*yk;
                }
                tmp /= dkyk;

                for (i = 0; i < n; i++) {
                    beta += ((gtemp[i]-g[i]) - 2*d[i]*tmp) * gtemp[i];
                }
                beta /= dkyk;

                break;
            }
        }

        if (args->heuristic_type == FMIN_CG_HEURISTICS_P) {
            beta = beta >= 0 ? beta : 0;
        } else if (args->heuristic_type == FMIN_CG_HEURISTICS_N) {
            dnorm = 0;
            gnorm = 0;
            for (i = 0; i < n; i++) {
                dnorm += d[i]*d[i];
                gnorm += g[i]*g[i];
            }
            tmp = -1/(dnorm * (0.01 < gnorm ? 0.01 : gnorm));
            beta = beta > tmp ? beta : tmp;
        }

        gnorm = 0;
        for (i = 0; i < n; i++) {
            d[i] = -gtemp[i] + beta*d[i];
            g[i] = gtemp[i];
#ifdef FMIN_CG_INF_NORM
            tmp = fabs(g[i]);
            gnorm = tmp > gnorm ? tmp : gnorm;
#else
            gnorm += g[i]*g[i];
#endif
        }
    }

    if (preallocated) {
        free(work_array);
    }

    printf("i=%d f=%d g=%d", vars.niterations, vars.nval, vars.ngrad);

    return x;
}
Example #11
0
  int
  MilpRounding::solution(double &solutionValue, double *betterSolution)
  {
    if(model_->getCurrentPassNumber() > 1) return 0;
    if (model_->currentDepth() > 2 && (model_->getNodeCount()%howOften_)!=0)
      return 0;
 
    int returnCode = 0; // 0 means it didn't find a feasible solution

    OsiTMINLPInterface * nlp = NULL;
    if(setup_->getAlgorithm() == B_BB)
      nlp = dynamic_cast<OsiTMINLPInterface *>(model_->solver()->clone());
    else
      nlp = dynamic_cast<OsiTMINLPInterface *>(setup_->nonlinearSolver()->clone());

    TMINLP2TNLP* minlp = nlp->problem();
 
    // set tolerances
    double integerTolerance = model_->getDblParam(CbcModel::CbcIntegerTolerance);
    //double primalTolerance = 1.0e-6;

    int n;
    int m;
    int nnz_jac_g;
    int nnz_h_lag;
    Ipopt::TNLP::IndexStyleEnum index_style;
    minlp->get_nlp_info(n, m, nnz_jac_g,
			nnz_h_lag, index_style);

    const Bonmin::TMINLP::VariableType* variableType = minlp->var_types();
    const double* x_sol = minlp->x_sol();
    const double* g_l = minlp->g_l();
    const double* g_u = minlp->g_u();

    const double * colsol = model_->solver()->getColSolution();


    // Get information about the linear and nonlinear part of the instance
    TMINLP* tminlp = nlp->model();
    vector<Ipopt::TNLP::LinearityType> c_lin(m);
    tminlp->get_constraints_linearity(m, c_lin());
    vector<int> c_idx(m);
    int n_lin = 0;
    for (int i=0;i<m;i++) {
      if (c_lin[i]==Ipopt::TNLP::LINEAR)
	c_idx[i] = n_lin++;
      else
	c_idx[i] = -1;
    }


    // Get the structure of the jacobian
    vector<int> indexRow(nnz_jac_g);
    vector<int> indexCol(nnz_jac_g);
    minlp->eval_jac_g(n, x_sol, false,
		      m, nnz_jac_g,
		      indexRow(), indexCol(), 0);

    // get the jacobian values 
    vector<double> jac_g(nnz_jac_g);
    minlp->eval_jac_g(n, x_sol, false,
                      m, nnz_jac_g,
                      NULL, NULL, jac_g());

    // Sort the matrix to column ordered
    vector<int> sortedIndex(nnz_jac_g);
    CoinIotaN(sortedIndex(), nnz_jac_g, 0);
    MatComp c;
    c.iRow = indexRow();
    c.jCol = indexCol();
    std::sort(sortedIndex.begin(), sortedIndex.end(), c);

    vector<int> row (nnz_jac_g);
    vector<double> value (nnz_jac_g);
    vector<int> columnStart(n,0); 
    vector<int> columnLength(n,0);
    int indexCorrection = (index_style == Ipopt::TNLP::C_STYLE) ? 0 : 1;
    int iniCol = -1;
    int nnz = 0;
    for(int i=0; i<nnz_jac_g; i++) {
      int thisIndexCol = indexCol[sortedIndex[i]]-indexCorrection;
      int thisIndexRow = c_idx[indexRow[sortedIndex[i]] - indexCorrection];
      if(thisIndexCol != iniCol) {
	iniCol = thisIndexCol;
	columnStart[thisIndexCol] = nnz;
	columnLength[thisIndexCol] = 0;
      }
      if(thisIndexRow == -1) continue;
      columnLength[thisIndexCol]++;
      row[nnz] = thisIndexRow;
      value[nnz] = jac_g[i];
      nnz++;
    }

    // Build the row lower and upper bounds
    vector<double> newRowLower(n_lin);
    vector<double> newRowUpper(n_lin);
    for(int i = 0 ; i < m ; i++){
      if(c_idx[i] == -1) continue;
      newRowLower[c_idx[i]] = g_l[i];
      newRowUpper[c_idx[i]] = g_u[i];
    }

    // Get solution array for heuristic solution
    vector<double> newSolution(n);
    std::copy(x_sol, x_sol + n, newSolution.begin());

    // Define the constraint matrix for MILP
    CoinPackedMatrix matrix(true,n_lin,n, nnz, value(), row(), columnStart(), columnLength());

      // create objective function and columns lower and upper bounds for MILP
      // and create columns for matrix in MILP
      //double alpha = 0;
      double beta = 1;
      vector<double> objective(n);
      vector<int> idxIntegers;
      idxIntegers.reserve(n);
      for(int i = 0 ; i < n ; i++){
         if(variableType[i] != Bonmin::TMINLP::CONTINUOUS){
            idxIntegers.push_back(i);
            objective[i] = beta*(1 - 2*colsol[i]);
         }
      }

#if 0
      // Get dual multipliers and build gradient of the lagrangean
      const double * duals = nlp->getRowPrice() + 2 *n;
      vector<double> grad(n, 0); 
      vector<int> indices(n, 0);
      tminlp->eval_grad_f(n, x_sol, false, grad());
      for(int i = 0 ; i < m ; i++){
        if(c_lin[i] == Ipopt::TNLP::LINEAR) continue;
        int nnz;
        tminlp->eval_grad_gi(n, x_sol, false, i, nnz, indices(), NULL);  
        tminlp->eval_grad_gi(n, x_sol, false, i, nnz, NULL, grad());
        for(int k = 0 ; k < nnz ; k++){
          objective[indices[k]] += alpha *duals[i] * grad[k];
        } 
      }
      for(int i = 0 ; i < n ; i++){
         if(variableType[i] != Bonmin::TMINLP::CONTINUOUS)
         objective[i] += alpha * grad[i];
         //if(fabs(objective[i]) < 1e-4) objective[i] = 0;
         else objective[i] = 0;
      }
      std::copy(objective.begin(), objective.end(), std::ostream_iterator<double>(std::cout, " "));
      std::cout<<std::endl;
#endif

      // load the problem to OSI
      OsiSolverInterface *si = mip_->solver();
      assert(si != NULL);
      CoinMessageHandler * handler = model_->messageHandler()->clone();
      si->passInMessageHandler(handler);
      si->messageHandler()->setLogLevel(1);

      si->loadProblem(matrix, model_->solver()->getColLower(), model_->solver()->getColUpper(), objective(), 
                      newRowLower(), newRowUpper());
      si->setInteger(idxIntegers(), static_cast<int>(idxIntegers.size()));
      si->applyCuts(noGoods);

      bool hasFractionnal = true;
      while(hasFractionnal){
        mip_->optimize(DBL_MAX, 0, 60);
        hasFractionnal = false;
#if 0
        bool feasible = false;
        if(mip_->getLastSolution()) {
  	const double* solution = mip_->getLastSolution();
          std::copy(solution, solution + n, newSolution.begin());
  	feasible = true;
  
        }

    if(feasible) {
      // fix the integer variables and solve the NLP
      // also add no good cut
      CoinPackedVector v;
      double lb = 1;
      for (int iColumn=0;iColumn<n;iColumn++) {
	if (variableType[iColumn] != Bonmin::TMINLP::CONTINUOUS) {
	  double value=newSolution[iColumn];
	  if (fabs(floor(value+0.5)-value)>integerTolerance) {
#ifdef DEBUG_BON_HEURISTIC_DIVE_MIP
	    cout<<"It should be infeasible because: "<<endl;
	    cout<<"variable "<<iColumn<<" is not integer"<<endl;
#endif
	    feasible = false;
	    break;
	  }
	  else {
	    value=floor(newSolution[iColumn]+0.5);
            if(value > 0.5){
              v.insert(iColumn, -1);
              lb -= value;
            }
	    minlp->SetVariableUpperBound(iColumn, value);
	    minlp->SetVariableLowerBound(iColumn, value);
	  }
	}
      }
      }
#endif
      }
      bool feasible = false;
      if(mip_->getLastSolution()) {
	const double* solution = mip_->getLastSolution();
        std::copy(solution, solution + n, newSolution.begin());
	feasible = true;

        delete handler;
      }
      

    if(feasible) {
      // fix the integer variables and solve the NLP
      // also add no good cut
      CoinPackedVector v;
      double lb = 1;
      for (int iColumn=0;iColumn<n;iColumn++) {
	if (variableType[iColumn] != Bonmin::TMINLP::CONTINUOUS) {
	  double value=newSolution[iColumn];
	  if (fabs(floor(value+0.5)-value)>integerTolerance) {
	    feasible = false;
	    break;
	  }
	  else {
	    value=floor(newSolution[iColumn]+0.5);
            if(value > 0.5){
              v.insert(iColumn, -1);
              lb -= value;
            }
	    minlp->SetVariableUpperBound(iColumn, value);
	    minlp->SetVariableLowerBound(iColumn, value);
	  }
	}
      }
      OsiRowCut c;
      c.setRow(v);
      c.setLb(lb);
      c.setUb(DBL_MAX);
      noGoods.insert(c);
      if(feasible) {
	nlp->initialSolve();
	if(minlp->optimization_status() != Ipopt::SUCCESS) {
	  feasible = false;
	}
	std::copy(x_sol,x_sol+n, newSolution.begin());
      }
    }
    if(feasible) {
      double newSolutionValue;
      minlp->eval_f(n, newSolution(), true, newSolutionValue); 
      if(newSolutionValue < solutionValue) {
        std::copy(newSolution.begin(), newSolution.end(), betterSolution);
	solutionValue = newSolutionValue;
	returnCode = 1;
      }
    }

    delete nlp;

#ifdef DEBUG_BON_HEURISTIC_DIVE_MIP
    std::cout<<"DiveMIP returnCode = "<<returnCode<<std::endl;
#endif

    return returnCode;
  }
Example #12
0
Vector3d ImpSurface::normal (const Point3d& location)
{
	return grad(location).normalize();
}