Esempio n. 1
0
/*!
    \fn QDBusMetaType::typeToSignature(int type)
    \internal 

    Returns the D-Bus signature equivalent to the supplied meta type id \a type.

    More types can be registered with the qDBusRegisterMetaType() function.

    \sa QDBusUtil::isValidSingleSignature(), signatureToType(),
        QVariant::type(), QVariant::userType()
*/
const char *QDBusMetaType::typeToSignature(int type)
{
    // check if it's a static type
    switch (type)
    {
    case QMetaType::UChar:
        return DBUS_TYPE_BYTE_AS_STRING;

    case QVariant::Bool:
        return DBUS_TYPE_BOOLEAN_AS_STRING;

    case QMetaType::Short:
        return DBUS_TYPE_INT16_AS_STRING;

    case QMetaType::UShort:
        return DBUS_TYPE_UINT16_AS_STRING;

    case QVariant::Int:
        return DBUS_TYPE_INT32_AS_STRING;

    case QVariant::UInt:
        return DBUS_TYPE_UINT32_AS_STRING;

    case QVariant::LongLong:
        return DBUS_TYPE_INT64_AS_STRING;

    case QVariant::ULongLong:
        return DBUS_TYPE_UINT64_AS_STRING;

    case QVariant::Double:
        return DBUS_TYPE_DOUBLE_AS_STRING;

    case QVariant::String:
        return DBUS_TYPE_STRING_AS_STRING;

    case QVariant::StringList:
        return DBUS_TYPE_ARRAY_AS_STRING
            DBUS_TYPE_STRING_AS_STRING; // as

    case QVariant::ByteArray:
        return DBUS_TYPE_ARRAY_AS_STRING
            DBUS_TYPE_BYTE_AS_STRING; // ay
    }

    QDBusMetaTypeId::init();
    if (type == QDBusMetaTypeId::variant)
        return DBUS_TYPE_VARIANT_AS_STRING;
    else if (type == QDBusMetaTypeId::objectpath)
        return DBUS_TYPE_OBJECT_PATH_AS_STRING;
    else if (type == QDBusMetaTypeId::signature)
        return DBUS_TYPE_SIGNATURE_AS_STRING;

    // try the database
    QVector<QDBusCustomTypeInfo> *ct = customTypes();
    {
        QReadLocker locker(customTypesLock());
        if (type >= ct->size())
            return 0;           // type not registered with us

        const QDBusCustomTypeInfo &info = (*ct).at(type);

        if (!info.signature.isNull())
            return info.signature;

        if (!info.marshall)
            return 0;           // type not registered with us
    }

    // call to user code to construct the signature type
    QDBusCustomTypeInfo *info;
    {
        // createSignature will never return a null QByteArray
        // if there was an error, it'll return ""
        QByteArray signature = QDBusArgumentPrivate::createSignature(type);

        // re-acquire lock
        QWriteLocker locker(customTypesLock());
        info = &(*ct)[type];
        info->signature = signature;
    }
    return info->signature;
}
Esempio n. 2
0
void GLWidget::paintGL()
{
    int width = this->width() * devicePixelRatio();
    int height = this->height() * devicePixelRatio();

    glDisable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    glDepthMask(GL_FALSE);
    glViewport(0, 0, width, height);
    check_error();
    QColor color = QPalette().color(QPalette::Window);
    glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
    glClear(GL_COLOR_BUFFER_BIT);
    check_error();

    if (!m_texture[0]) return;

    // Bind textures.
    for (int i = 0; i < 3; ++i) {
        if (m_texture[i]) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, m_texture[i]);
            check_error();
        }
    }

    // Init shader program.
    m_shader->bind();
    if (m_glslManager) {
        m_shader->setUniformValue(m_textureLocation[0], 0);
    } else {
        m_shader->setUniformValue(m_textureLocation[0], 0);
        m_shader->setUniformValue(m_textureLocation[1], 1);
        m_shader->setUniformValue(m_textureLocation[2], 2);
        m_shader->setUniformValue(m_colorspaceLocation, MLT.profile().colorspace());
    }
    check_error();

    // Setup an orthographic projection.
    QMatrix4x4 projection;
    projection.scale(2.0f / width, 2.0f / height);
    m_shader->setUniformValue(m_projectionLocation, projection);
    check_error();

    // Set model view.
    QMatrix4x4 modelView;
    if (m_zoom > 0.0) {
        if (offset().x() || offset().y())
            modelView.translate(-offset().x() * devicePixelRatio(),
                                 offset().y() * devicePixelRatio());
        modelView.scale(zoom(), zoom());
    }
    m_shader->setUniformValue(m_modelViewLocation, modelView);
    check_error();

    // Provide vertices of triangle strip.
    QVector<QVector2D> vertices;
    width = m_rect.width() * devicePixelRatio();
    height = m_rect.height() * devicePixelRatio();
    vertices << QVector2D(float(-width)/2.0f, float(-height)/2.0f);
    vertices << QVector2D(float(-width)/2.0f, float( height)/2.0f);
    vertices << QVector2D(float( width)/2.0f, float(-height)/2.0f);
    vertices << QVector2D(float( width)/2.0f, float( height)/2.0f);
    m_shader->enableAttributeArray(m_vertexLocation);
    check_error();
    m_shader->setAttributeArray(m_vertexLocation, vertices.constData());
    check_error();

    // Provide texture coordinates.
    QVector<QVector2D> texCoord;
    texCoord << QVector2D(0.0f, 1.0f);
    texCoord << QVector2D(0.0f, 0.0f);
    texCoord << QVector2D(1.0f, 1.0f);
    texCoord << QVector2D(1.0f, 0.0f);
    m_shader->enableAttributeArray(m_texCoordLocation);
    check_error();
    m_shader->setAttributeArray(m_texCoordLocation, texCoord.constData());
    check_error();

    // Render
    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size());
    check_error();

    // Cleanup
    m_shader->disableAttributeArray(m_vertexLocation);
    m_shader->disableAttributeArray(m_texCoordLocation);
    m_shader->release();
    for (int i = 0; i < 3; ++i) {
        if (m_texture[i]) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, 0);
            check_error();
        }
    }
    glActiveTexture(GL_TEXTURE0);
    check_error();
}
void GeometryEngine::initGeometry(TriangleList triangles, QVector<QVector3D> lines, QVector<QVector3D> points)
{
    isTransparent = false;

    initializeOpenGLFunctions();

    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Generate 2 VBOs
    arrayBuf.create();
    indexBuf.create();
    arrayBufLines.create();
    arrayBufPoints.create();

    std::vector<VertexData> vertices;
    std::vector<GLuint> indices;
    std::vector<GLuint> tmp(3);

    // iterate over all triangles
    for (uint i = 0; i < triangles.size(); i++) {
        // iterate over all vertices in triangle
        for (int j = 0; j < 3; j++) {
            // create vertex with texture coords
            VertexData vertex = {
                QVector3D(triangles[i][j][0], triangles[i][j][1], triangles[i][j][2]),
                QVector2D(abs(((j+1)%2)-1), abs(((j+1)%3)-1)) // tex coords (0,0),(1,1),(0,1)
            };

            // is vertex already in indices?
            GLuint idx = indexOf(vertices, vertex);
            if (idx >= vertices.size()) {
                // no, add it to the end of the list
                //idx = vertices.size();
                vertices.push_back(vertex);
            }
            // prime the index of current vertex for insertion
            tmp[j] = idx;
        }
        // insert vertex indices of current triangle
        indices.insert(indices.end(), tmp.begin(), tmp.end());

        // render both sides of triangles, for now as a #define option
#if TWO_SIDED
        std::reverse(tmp.begin(), tmp.end());
        indices.insert(indices.end(), tmp.begin(), tmp.end());
#endif
    }

#if DEBUG
    std::cout << "Vertices:" << std::endl << vertices.size() << std::endl;
    for (auto i = vertices.begin(); i != vertices.end(); ++i)
        std::cout << "(" << (*i).position[0] <<"," << (*i).position[1] <<"," << (*i).position[2] <<")" << ' ';
    std::cout << std::endl;

    std::cout << "Indices:" << std::endl << indices.size() << std::endl;
    for (auto i = indices.begin(); i != indices.end(); ++i)
        std::cout << *i << ' ';
    std::cout << std::endl;
#endif

    arrayBuf.bind();
    arrayBuf.allocate(&vertices[0], vertices.size() * sizeof(VertexData));

    indexBuf.bind();
    indexBuf.allocate(&indices[0], indices.size() * sizeof(GLuint));

    idxLen = indices.size();

    if (!lines.empty())
    {
        arrayBufLines.bind();
        arrayBufLines.allocate(&lines[0], lines.size() * sizeof(QVector3D));
    }

    if (!points.empty())
    {
        arrayBufPoints.bind();
        arrayBufPoints.allocate(&points[0], points.size() * sizeof(QVector3D));
    }
}
Esempio n. 4
0
int UIDnDHandler::dragCheckPending(ulong screenID)
{
    int rc;
#ifdef VBOX_WITH_DRAG_AND_DROP_GH

    LogFlowFunc(("enmMode=%RU32, fIsPending=%RTbool, screenID=%RU32\n", m_enmMode, m_fIsPending, screenID));

    {
        QMutexLocker AutoReadLock(&m_ReadLock);

        if (   m_enmMode != DNDMODE_UNKNOWN
            && m_enmMode != DNDMODE_GUESTTOHOST) /* Wrong mode set? */
            return VINF_SUCCESS;

        if (m_fIsPending) /* Pending operation is in progress. */
            return VINF_SUCCESS;
    }

    QMutexLocker AutoWriteLock(&m_WriteLock);
    m_fIsPending = true;
    AutoWriteLock.unlock();

    /**
     * How this works: Source is asking the target if there is any DnD
     * operation pending, when the mouse leaves the guest window. On
     * return there is some info about a running DnD operation
     * (or defaultAction is KDnDAction_Ignore if not). With
     * this information we create a Qt QDrag object with our own QMimeType
     * implementation and call exec.
     *
     * Note: This function *blocks* until the actual drag'n drop operation
     *       has been finished (successfully or not)!
     */
    CGuest guest = m_pSession->guest();

    /* Clear our current data set. */
    m_dataSource.lstFormats.clear();
    m_dataSource.vecActions.clear();

    /* Ask the guest if there is a drag and drop operation pending (on the guest). */
    QVector<QString> vecFormats;
    m_dataSource.defaultAction = m_dndSource.DragIsPending(screenID, vecFormats, m_dataSource.vecActions);

    LogRelMax3(10, ("DnD: Default action is: 0x%x\n", m_dataSource.defaultAction));
    LogRelMax3(10, ("DnD: Number of supported guest actions: %d\n", m_dataSource.vecActions.size()));
        for (int i = 0; i < m_dataSource.vecActions.size(); i++)
            LogRelMax3(10, ("DnD: \tAction %d: 0x%x\n", i, m_dataSource.vecActions.at(i)));

    LogRelMax3(10, ("DnD: Number of supported guest formats: %d\n", vecFormats.size()));
        for (int i = 0; i < vecFormats.size(); i++)
        {
            const QString &strFmtGuest = vecFormats.at(i);
            LogRelMax3(10, ("DnD: \tFormat %d: %s\n", i, strFmtGuest.toAscii().constData()));
        }

    LogFlowFunc(("defaultAction=0x%x, vecFormatsSize=%d, vecActionsSize=%d\n",
                 m_dataSource.defaultAction, vecFormats.size(), m_dataSource.vecActions.size()));

    if (   m_dataSource.defaultAction != KDnDAction_Ignore
        && vecFormats.size())
    {
        for (int i = 0; i < vecFormats.size(); i++)
        {
            const QString &strFormat = vecFormats.at(i);
            m_dataSource.lstFormats << strFormat;
        }

        rc = VINF_SUCCESS; /* There's a valid pending drag and drop operation on the guest. */
    }
    else /* No format data from the guest arrived yet. */
        rc = VERR_NO_DATA;

    AutoWriteLock.relock();
    m_fIsPending = false;
    AutoWriteLock.unlock();

#else /* !VBOX_WITH_DRAG_AND_DROP_GH */

    NOREF(screenID);

    rc = VERR_NOT_SUPPORTED;

#endif /* VBOX_WITH_DRAG_AND_DROP_GH */

    LogFlowFuncLeaveRC(rc);
    return rc;
}
Esempio n. 5
0
// TODO: Build own exporter class
void objectExporter::on_buttonBox_accepted()
{
    QString fileName = QFileDialog::getSaveFileName(gloParent, "Save 3ds Object", ".", "3D Object (*.3ds)", 0, 0);

    QList<trackHandler*> trackList = gloParent->getTrackList();
    trackHandler* curTrack = trackList[ui->trackBox->currentIndex()];

    trackMesh* mesh = curTrack->mMesh;

    QVector<float> *vertices = new QVector<float>();
    QVector<unsigned int> *indices = new QVector<unsigned int>();
    QVector<unsigned int> *borders = new QVector<unsigned int>();

    Lib3dsFile *file = lib3ds_file_new();
    file->frames = 360;

    {
        Lib3dsMaterial* mat = lib3ds_material_new("coaster");
        lib3ds_file_insert_material(file, mat, -1);
        mat->diffuse[0] = curTrack->trackColors[0].red()/255.f;
        mat->diffuse[1] = curTrack->trackColors[0].green()/255.f;
        mat->diffuse[2] = curTrack->trackColors[0].blue()/255.f;
    }

    {
        for(int section = 0; section < curTrack->trackData->lSections.size(); ++section) {
            vertices->clear();
            indices->clear();
            borders->clear();
            mesh->build3ds(section, vertices, indices, borders);

            float* fvertices = new float[vertices->size()];
            for(int i = 0; i < vertices->size()/3; ++i) {
                fvertices[3*i+0] = vertices->at(3*i+0);
                fvertices[3*i+1] = -vertices->at(3*i+2);
                fvertices[3*i+2] = vertices->at(3*i+1);

                //exportScreen->doFastExport();
            }
            for(int subIndex = 0; subIndex < borders->size()-2; subIndex+= 2) {
                int fromVIndex = borders->at(subIndex)/3;
                int toVIndex = borders->at(subIndex+2)/3;
                int fromIIndex = borders->at(subIndex+1)/3;
                int toIIndex = borders->at(subIndex+3)/3;

                int i, j;
                QString name = QString::number(section).append(QString("_").append(QString::number(subIndex/2)));
                Lib3dsMesh *mesh = lib3ds_mesh_new(name.toLocal8Bit().data());
                Lib3dsMeshInstanceNode *inst;
                lib3ds_file_insert_mesh(file, mesh, -1);

                lib3ds_mesh_resize_vertices(mesh, toVIndex-fromVIndex, 1, 0);
                for (i = 0; i < toVIndex-fromVIndex; ++i) {
                    lib3ds_vector_copy(mesh->vertices[i], &fvertices[(i+fromVIndex)*3]);
                    mesh->texcos[i][0] = 0.f;
                    mesh->texcos[i][1] = 0.f;
                }

                lib3ds_mesh_resize_faces(mesh, toIIndex-fromIIndex);
                for (i = 0; i < toIIndex-fromIIndex; ++i) {
                    for (j = 0; j < 3; ++j) {
                        mesh->faces[i].index[j] = indices->at(3*(i+fromIIndex)+j)-fromVIndex;
                        mesh->faces[i].material = 0;
                    }
                }
                inst = lib3ds_node_new_mesh_instance(mesh, name.toLocal8Bit().data(), NULL, NULL, NULL);
                lib3ds_file_append_node(file, (Lib3dsNode*)inst, NULL);
            }
            delete[] fvertices;
        }
    }

    {
        Lib3dsCamera *camera;
        Lib3dsCameraNode *n;
        Lib3dsTargetNode *t;
        int i;

        camera = lib3ds_camera_new("camera01");
        lib3ds_file_insert_camera(file, camera, -1);
        lib3ds_vector_make(camera->position, 0.0, -100, 0.0);
        lib3ds_vector_make(camera->target, 0.0, 0.0, 0.0);

        n = lib3ds_node_new_camera(camera);
        t = lib3ds_node_new_camera_target(camera);
        lib3ds_file_append_node(file, (Lib3dsNode*)n, NULL);
        lib3ds_file_append_node(file, (Lib3dsNode*)t, NULL);

        lib3ds_track_resize(&n->pos_track, 37);
        for (i = 0; i <= 36; i++) {
            n->pos_track.keys[i].frame = 10 * i;
            lib3ds_vector_make(n->pos_track.keys[i].value,
                (float)(100.0 * cos(2 * F_PI * i / 36.0)),
                (float)(100.0 * sin(2 * F_PI * i / 36.0)),
                50.0
            );
        }
    }

    if (!lib3ds_file_save(file, fileName.toLocal8Bit().data())) {
         qDebug("ERROR: Saving 3ds file failed!\n");
    }
    lib3ds_file_free(file);

    delete indices;
    delete vertices;
}
Esempio n. 6
0
void QSvgText::draw(QPainter *p, QSvgExtraStates &states)
{
    applyStyle(p, states);
    qreal oldOpacity = p->opacity();
    p->setOpacity(oldOpacity * states.fillOpacity);

    // Force the font to have a size of 100 pixels to avoid truncation problems
    // when the font is very small.
    qreal scale = 100.0 / p->font().pointSizeF();
    Qt::Alignment alignment = states.textAnchor;

    QTransform oldTransform = p->worldTransform();
    p->scale(1 / scale, 1 / scale);

    qreal y = 0;
    bool initial = true;
    qreal px = m_coord.x() * scale;
    qreal py = m_coord.y() * scale;
    QSizeF scaledSize = m_size * scale;

    if (m_type == TEXTAREA) {
        if (alignment == Qt::AlignHCenter)
            px += scaledSize.width() / 2;
        else if (alignment == Qt::AlignRight)
            px += scaledSize.width();
    }

    QRectF bounds;
    if (m_size.height() != 0)
        bounds = QRectF(0, py, 1, scaledSize.height()); // x and width are not used.

    bool appendSpace = false;
    QVector<QString> paragraphs;
    QStack<QTextCharFormat> formats;
    QVector<QList<QTextLayout::FormatRange> > formatRanges;
    paragraphs.push_back(QString());
    formatRanges.push_back(QList<QTextLayout::FormatRange>());

    for (int i = 0; i < m_tspans.size(); ++i) {
        if (m_tspans[i] == LINEBREAK) {
            if (m_type == TEXTAREA) {
                if (paragraphs.back().isEmpty()) {
                    QFont font = p->font();
                    font.setPixelSize(font.pointSizeF() * scale);

                    QTextLayout::FormatRange range;
                    range.start = 0;
                    range.length = 1;
                    range.format.setFont(font);
                    formatRanges.back().append(range);

                    paragraphs.back().append(QLatin1Char(' '));;
                }
                appendSpace = false;
                paragraphs.push_back(QString());
                formatRanges.push_back(QList<QTextLayout::FormatRange>());
            }
        } else {
            WhitespaceMode mode = m_tspans[i]->whitespaceMode();
            m_tspans[i]->applyStyle(p, states);

            QFont font = p->font();
            font.setPixelSize(font.pointSizeF() * scale);

            QString newText(m_tspans[i]->text());
            newText.replace(QLatin1Char('\t'), QLatin1Char(' '));
            newText.replace(QLatin1Char('\n'), QLatin1Char(' '));

            bool prependSpace = !appendSpace && !m_tspans[i]->isTspan() && (mode == Default) && !paragraphs.back().isEmpty() && newText.startsWith(QLatin1Char(' '));
            if (appendSpace || prependSpace)
                paragraphs.back().append(QLatin1Char(' '));

            bool appendSpaceNext = (!m_tspans[i]->isTspan() && (mode == Default) && newText.endsWith(QLatin1Char(' ')));

            if (mode == Default) {
                newText = newText.simplified();
                if (newText.isEmpty())
                    appendSpaceNext = false;
            }

            QTextLayout::FormatRange range;
            range.start = paragraphs.back().length();
            range.length = newText.length();
            range.format.setFont(font);
            range.format.setTextOutline(p->pen());
            range.format.setForeground(p->brush());

            if (appendSpace) {
                Q_ASSERT(!formatRanges.back().isEmpty());
                ++formatRanges.back().back().length;
            } else if (prependSpace) {
                --range.start;
                ++range.length;
            }
            formatRanges.back().append(range);

            appendSpace = appendSpaceNext;
            paragraphs.back() += newText;

            m_tspans[i]->revertStyle(p, states);
        }
    }

    if (states.svgFont) {
        // SVG fonts not fully supported...
        QString text = paragraphs.front();
        for (int i = 1; i < paragraphs.size(); ++i) {
            text.append(QLatin1Char('\n'));
            text.append(paragraphs[i]);
        }
        states.svgFont->draw(p, m_coord * scale, text, p->font().pointSizeF() * scale, states.textAnchor);
    } else {
        for (int i = 0; i < paragraphs.size(); ++i) {
            QTextLayout tl(paragraphs[i]);
            QTextOption op = tl.textOption();
            op.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
            tl.setTextOption(op);
            tl.setAdditionalFormats(formatRanges[i]);
            tl.beginLayout();

            forever {
                QTextLine line = tl.createLine();
                if (!line.isValid())
                    break;
                if (m_size.width() != 0)
                    line.setLineWidth(scaledSize.width());
            }
            tl.endLayout();

            bool endOfBoundsReached = false;
            for (int i = 0; i < tl.lineCount(); ++i) {
                QTextLine line = tl.lineAt(i);

                qreal x = 0;
                if (alignment == Qt::AlignHCenter)
                    x -= 0.5 * line.naturalTextWidth();
                else if (alignment == Qt::AlignRight)
                    x -= line.naturalTextWidth();

                if (initial && m_type == TEXT)
                    y -= line.ascent();
                initial = false;

                line.setPosition(QPointF(x, y));

                // Check if the current line fits into the bounding rectangle.
                if ((m_size.width() != 0 && line.naturalTextWidth() > scaledSize.width())
                    || (m_size.height() != 0 && y + line.height() > scaledSize.height())) {
                    // I need to set the bounds height to 'y-epsilon' to avoid drawing the current
                    // line. Since the font is scaled to 100 units, 1 should be a safe epsilon.
                    bounds.setHeight(y - 1);
                    endOfBoundsReached = true;
                    break;
                }

                y += 1.1 * line.height();
            }
            tl.draw(p, QPointF(px, py), QVector<QTextLayout::FormatRange>(), bounds);

            if (endOfBoundsReached)
                break;
        }
    }

    p->setWorldTransform(oldTransform, false);
    p->setOpacity(oldOpacity);
    revertStyle(p, states);
}
Esempio n. 7
0
int BarPlot::plotOther()
{
	string dataType = Node->getFirst();

	// Get the types
	// Note the type is not always going to be the within the children of the node (depending on what node is passed)
	// It will be possible to pass in a different node (say a publication type node) when implemented
	vector<node*> types;
	if (Node->getParent() == NULL){
		vector<node*>* temptypes = Node->getChildren();
		for (int i = 0; i < temptypes->size(); i++){
			if (temptypes->at(i)->getSecond() > 0)
				types.push_back(temptypes->at(i));
		}
	}
	else{ types.push_back(Node);}

	// Grab Data and prepare x axis with (professor Name) labels:
	QVector<QString> labels;
	// Search for the prof names
	for (int i = 0; i < types.size(); i++){
		for (int j = 0; j < types.at(i)->getChildren()->size(); j++){
			QString name = QString::fromStdString(types.at(i)->getChildren()->at(j)->getFirst());
			if (!(labels.contains(name)))
				labels.push_back(name);
		}
	}

	// stacked bar chart can get cluttered, ensure no more than 30 different types
	// determine which types to push into an "Others" group
	vector<int> othersNdx;
	if (types.size() > COUNT_MAX){
		vector<double> typeSumCounts;
		for (int i = 0; i < types.size(); i++){
			if (Node->getFourth() > 0.0)
				typeSumCounts.push_back(types.at(i)->getFourth());
			else
				typeSumCounts.push_back(types.at(i)->getSecond());
		}
		while (types.size() - othersNdx.size() > COUNT_MAX){
			othersNdx.push_back(min_element(typeSumCounts.begin(), typeSumCounts.end()) - typeSumCounts.begin());
			typeSumCounts.at(min_element(typeSumCounts.begin(), typeSumCounts.end()) - typeSumCounts.begin()) = std::numeric_limits<double>::infinity();
		}
	}

	QVector<double> ticks;
	for (int i = 1; i <= labels.size(); i++)
		ticks.push_back(i);

	vector<QCPBars*> bars;
	QVector<double> othersCount(labels.size());
	double *othersData = othersCount.data();
	// create a new plottable area for each type, group everything within the "Others" group together
	for (int i = 0; i < types.size(); i++)
	{
		QVector<double> count(labels.size());
		double *data = count.data();
		// Note: not all types have same number of children (profs)
		// this would affect the labels (prof names)
		for (int j = 0; j < types.at(i)->getChildren()->size(); j++){
			int pos = labels.indexOf(QString::fromStdString(types.at(i)->getChildren()->at(j)->getFirst()));
			if (Node->getFourth() > 0.0)
				data[pos] = types.at(i)->getChildren()->at(j)->getFourth();
			else
				data[pos] = types.at(i)->getChildren()->at(j)->getSecond();
		}


		QCPBars *temp = new QCPBars(this->xAxis, this->yAxis);

		if (std::find(othersNdx.begin(), othersNdx.end(), i) != othersNdx.end()){
			for (int j = 0; j < labels.size(); j++)
				othersData[j] += count[j];
		}
		else{
			temp->setName(QString::fromStdString(types.at(i)->getFirst()));
			temp->setData(ticks, count);
			bars.push_back(temp);
			this->addPlottable(temp);
		}
	}
	// Graph "Others" only if there's something in it
	if (std::find(othersCount.begin(), othersCount.end(), (!0)) != othersCount.end()){
		QCPBars *temp = new QCPBars(this->xAxis, this->yAxis);
		temp->setName("Others");
		temp->setData(ticks, othersCount);
		bars.push_back(temp);
		this->addPlottable(temp);
	}
	// stack bars ontop of each other:
	// loop through each of the QCPBar objects in the list bars
	if (bars.size() > 1){
		for (int i = 0; i < (bars.size() - 1); i++)
			bars[i + 1]->moveAbove(bars[i]);
	}
	// set the colors
	QPen pen;
	pen.setWidthF(1.2);
	int C_HUE = 0;
	for (int i = 0; i < bars.size(); i++)
	{
		QColor color_brush, color_pen;
		color_brush.setHsv(C_HUE, BAR_SAT, BAR_VAL);
		color_brush.setAlpha(BAR_ALPHA);
		color_pen.setHsv(C_HUE, BAR_SAT + 30, BAR_VAL + 10);
		color_pen.setAlpha(255);
		pen.setColor(color_pen);
		bars[i]->setPen(pen);
		bars[i]->setBrush(color_brush);
		C_HUE += HUE_MAX / bars.size();
	}

	//this->plotLayout()->addElement(0, 0, new QCPPlotTitle(this, QString::fromStdString(dataType)));
	// prepare x axis:
	this->xAxis->setAutoTicks(false);
	this->xAxis->setAutoTickLabels(false);
	this->xAxis->setTickVector(ticks);
	this->xAxis->setTickVectorLabels(labels);
	this->xAxis->setTickLabelRotation(60);
	this->xAxis->setSubTickCount(0);
	this->xAxis->setTickLength(0, 3);
	this->xAxis->grid()->setVisible(true);


	// prepare y axis:
	this->yAxis->setTickStep(5);
	this->yAxis->setPadding(5); // a bit more space to the left border
	if (Node->getFourth() > 0.0)
		this->yAxis->setLabel("Hours");
	else
		this->yAxis->setLabel("Count");
	this->yAxis->grid()->setSubGridVisible(true);
	QPen gridPen;
	gridPen.setStyle(Qt::SolidLine);
	gridPen.setColor(QColor(0, 0, 0, 25));
	this->yAxis->grid()->setPen(gridPen);
	gridPen.setStyle(Qt::DotLine);
	this->yAxis->grid()->setSubGridPen(gridPen);
	this->yAxis->scaleRange(1.3, this->yAxis->range().center());

	this->rescaleAxes(true);
	this->xAxis->setRange(0.5, 10.5);

	// setup legend:
	QCPLayoutGrid *subLayout = new QCPLayoutGrid;
	QCPLayoutElement *dummyElement = new QCPLayoutElement;

	this->plotLayout()->addElement(0, 1, subLayout); // add sub-layout in the cell to the right of the main axis rect
	subLayout->addElement(0, 0, this->legend); // add legend
	subLayout->addElement(1, 0, dummyElement); // add dummy element below legend
	subLayout->setRowStretchFactor(0, 0.01); // make legend cell (in row 0) take up as little vertical space as possible
	this->plotLayout()->setColumnStretchFactor(1, 0.01); // make the legend cell and dummy element column as small as possible

	this->legend->setVisible(true);
	this->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight);
	this->legend->setBrush(QColor(255, 255, 255, 200));
	QPen legendPen;
	legendPen.setColor(QColor(130, 130, 130, 200));
	this->legend->setBorderPen(legendPen);
	QFont legendFont = font();
	legendFont.setPointSize(8);
	this->legend->setFont(legendFont);
	this->legend->setSelectableParts(QCPLegend::spItems); // legend box shall not be selectable, only legend items

	this->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables | QCP::iSelectLegend);

	if (std::find(othersCount.begin(), othersCount.end(), (!0)) != othersCount.end()){
		return 1;
	}
	else
		return 0;
}
Esempio n. 8
0
void SCgModeBus::mousePressEvent (QGraphicsSceneMouseEvent * mouseEvent , bool afterSceneEvent)
{
    if(afterSceneEvent)
    {
        if(mDecoratedMode)
            mDecoratedMode->mousePressEvent(mouseEvent, afterSceneEvent);
        return;
    }

    mouseEvent->accept();
    QPointF mousePos = mouseEvent->scenePos();

    if (mPathItem && mouseEvent->button() == Qt::LeftButton)
        mPathItem->pushPoint(mousePos);

    // right button
    if (mouseEvent->button() == Qt::RightButton)
    {
        if (mPathItem)
        {
            mPathItem->popPoint();
            // if there is no points
            if (mPathItem->points().empty())
                delete mPathItem;
            return;
        }
    }

    if (mouseEvent->button() == Qt::LeftButton)
    {
        if (!mPathItem)
        {
            SCgVisualObject *obj = scene()->scgVisualObjectAt(mousePos);
            mNode = (obj != 0 && obj->type() == SCgVisualObject::SCgNodeType) ? static_cast<SCgVisualNode*>(obj) : 0;
            if(mNode)
            {
                mPathItem = new SCgPathItem(scene());
                mPathItem->pushPoint(mNode->scenePos());

                QPen pen;

                pen.setColor(Qt::blue);
                pen.setWidthF(5.f);
                pen.setCapStyle(Qt::RoundCap);
                pen.setStyle(Qt::DashDotLine);

                mPathItem->setPen(pen);
                return;
            }

        }else
        {
            QVector<QPointF> points = mPathItem->points();
            // The last point in points is mousePos, so we should get previous
            QVector2D vec(points.at(points.size() - 2) - mousePos);

            Q_ASSERT(mNode && mNode->baseObject() && mNode->baseObject()->type() == SCgObject::Node);
            if (points.size() > 2 && vec.length() < 5.f)
            {
                points.pop_back();

//                SCgVisualContour* contour = 0;
                // get parent contour
//                QGraphicsItem* parent = mNode->parentItem();

//                if (parent && parent->type() == SCgVisualContour::Type)
//                    contour = static_cast<SCgVisualContour*>(parent);

                scene()->pushCommand(new SCgCommandCreateBus(scene(), static_cast<SCgNode*>(mNode->baseObject()),
                                                                   points, 0));
                delete mPathItem;

                return;
            }
        }
    }

    if(mDecoratedMode)
    {
        mDecoratedMode->mousePressEvent(mouseEvent, afterSceneEvent);
        mPassMouseReleaseEvent = true;
    }
}
Esempio n. 9
0
// not threadsafe
bool DataFile::openForReWrite(const DataFile & other, const QString & filename, const QVector<unsigned> & chanNumSubset)
{
	if (!other.isOpenForRead()) {
		Error() << "INTERNAL ERROR: First parameter to DataFile::openForReWrite() needs to be another DataFile that is opened for reading.";
		return false;
	}
	if (isOpen()) closeAndFinalize();
	
	QString outputFile (filename);
	if (!QFileInfo(outputFile).isAbsolute())
        outputFile = mainApp()->outputDirectory() + "/" + outputFile; 
    
    Debug() << "outdir: " << mainApp()->outputDirectory() << " outfile: " << outputFile;
    
	dataFile.close();  metaFile.close();
    dataFile.setFileName(outputFile);
    metaFile.setFileName(metaFileForFileName(outputFile));
	
    if (!dataFile.open(QIODevice::WriteOnly|QIODevice::Truncate) ||
        !metaFile.open(QIODevice::WriteOnly|QIODevice::Truncate)) {
        Error() << "Failed to open either one or both of the data and meta files for " << outputFile;
        return false;
    }
	
//    badData = other.badData;
    badData.clear();
	mode = Output;
	const int nOnChans = chanNumSubset.size();
	params = other.params;
	params["outputFile"] = outputFile;
    params.remove("badData"); // rebuild this as we write!
	scanCt = 0;
	nChans = nOnChans;
	sha.Reset();
	sRate = other.sRate;
	range = other.range;
    writeRateAvg = 0.;
    nWritesAvg = 0;
    nWritesAvgMax = /*unsigned(sRate/10.)*/10;
    if (!nWritesAvgMax) nWritesAvgMax = 1;
	// compute save channel subset fudge
	const QVector<unsigned> ocid = other.channelIDs();
	chanIds.clear();
	customRanges.clear();
	chanDisplayNames.clear();
	QString crStr(""), cdnStr("");
	foreach (unsigned i, chanNumSubset) {
		if (i < unsigned(ocid.size())) {
			chanIds.push_back(ocid[i]);
			if (i < (unsigned)other.customRanges.size()) customRanges.push_back(other.customRanges[i]);
			else customRanges.push_back(range);
			if (i < (unsigned)other.chanDisplayNames.size()) chanDisplayNames.push_back(other.chanDisplayNames[i]);
			else chanDisplayNames.push_back(QString("Ch ") + QString::number(i));
			crStr.append(QString("%3%1:%2").arg(customRanges.back().min,0,'f',9).arg(customRanges.back().max,0,'f',9).arg(crStr.length() ? "," : ""));
			if (cdnStr.length()) cdnStr.append(",");
			cdnStr.append(QString(chanDisplayNames.back()).replace(",",""));
		} else 
			Error() << "INTERNAL ERROR: The chanNumSubset passet to DataFile::openForRead must be a subset of channel numbers (indices, not IDs) to use in the rewrite.";
	}
	params["saveChannelSubset"] = ConfigureDialogController::generateAIChanString(chanIds);
	params["nChans"] = nChans;
	if (params.contains("chanDisplayNames")) params["chanDisplayNames"] = cdnStr;
	if (params.contains("customRanges")) params["customRanges"] = crStr;
	pd_chanId = other.pd_chanId;
	
	return true;
}
Esempio n. 10
0
 /**
  *  Determines whether or not islands exist and calculates what they are if
  *  present
  */
 void ControlGraph::CalculateIslands()
 {
   // assume subgraphs exist! (check assumption at the very end of the method)
   
   // A search list has a value for every cube, which defaults to false.
   // A breadth-first search is used to test connectivity and works by setting
   // each cubes cooresponding search list value to true as it is visited.
   // At the end of the first round the true entries make up the first
   // subgragh.  As they are added to the first subgraph they are removed from
   // the search list.  The remaining false entries must have the breadth-first
   // search done on them to determine the next subgraph(s).  This process
   // continues until all entries in the search list are true (until all cubes
   // have been visited)
   QMap< int, bool > searchList;
   for (int i = 0; i < graph->size(); i++)
     searchList.insert(i, false);
 
   // For each subgraph keep a list of the cubes in the subgraph.  This is 
   // represented by a 2d vector where the inner vectors are cubes within a
   // subgraph and the outer vector is a list of subgraphs
   islands = new QVector< QVector< int > >();
   
   // keeps track of which itteration of the breadth-first search we are on and
   // thus also which subgraph we are currently populating
   int subgraphIndex = -1;
   
   while (searchList.size())
   {
     // create a new subgraph
     subgraphIndex++;
     islands->push_back(QVector< int >());
     
     // The queue used for breadth-first searching
     QQueue< int > q;
     
     // visit the first cube
     searchList.begin().value() = true;
     q.enqueue(searchList.begin().key());
     
     // visit all cubes possible using the breadth-first approach
     while (q.size())
     {
       int curVertex(q.dequeue());
       QVector< int > adjacentVertices = graph->find(curVertex).value().first
           .GetAdjacentCubes();
  
       for (int i = 0; i < adjacentVertices.size(); i++)
       {
         const int & curNeighbor = adjacentVertices[i];
         
         ASSERT(searchList.find(curNeighbor) != searchList.end());
         
         if (!searchList.find(curNeighbor).value())
         {
           searchList.find(curNeighbor).value() = true;
           q.enqueue(curNeighbor);
         }
       }
     } // end of breadth-first search
     
     // add all true entries to the current subgraph
     QMap< int, bool >::iterator i = searchList.begin();
     while (i != searchList.end())
     {
       if (i.value())
       {
         (*islands)[subgraphIndex].push_back(i.key());
       }
       i++;
     }
     
     // remove all the true entries from the search list
     for (int i = 0; i < (*islands)[subgraphIndex].size(); i++)
     {
       searchList.remove((*islands)[subgraphIndex][i]);
     }
   }
   
   // if there was only ever one subgraph created then the initial assumption
   // was wrong!  There are no islands at all - this is a connected graph!
   if (subgraphIndex == 0)
   {
     islands->clear();
   }
 }
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WritePoleFigure::execute()
{
  setErrorCondition(0);
  dataCheck();
  if(getErrorCondition() < 0) { return; }

  DataContainer::Pointer m = getDataContainerArray()->getDataContainer(m_CellPhasesArrayPath.getDataContainerName());

  size_t dims[3] = { 0, 0, 0 };
  m->getGeometryAs<ImageGeom>()->getDimensions(dims);

  // Make sure any directory path is also available as the user may have just typed
  // in a path without actually creating the full path
  QDir path(getOutputPath());

  if (!path.mkpath(".") )
  {
    QString ss = QObject::tr("Error creating parent path '%1'").arg(path.absolutePath());
    setErrorCondition(-1);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
    return;
  }

  bool missingGoodVoxels = true;

  if (NULL != m_GoodVoxels)
  {
    missingGoodVoxels = false;
  }

  // Find how many phases we have by getting the number of Crystal Structures
  size_t numPoints = m->getGeometryAs<ImageGeom>()->getNumberOfElements();
  size_t numPhases = m_CrystalStructuresPtr.lock()->getNumberOfTuples();

  // Loop over all the voxels gathering the Eulers for a specific phase into an array
  for (size_t phase = 1; phase < numPhases; ++phase)
  {
    size_t count = 0;
    // First find out how many voxels we are going to have. This is probably faster to loop twice than to
    // keep allocating memory everytime we find one.
    for (size_t i = 0; i < numPoints; ++i)
    {
      if (m_CellPhases[i] == phase)
      {
        if (missingGoodVoxels == true || m_GoodVoxels[i] == true)
        {
          count++;
        }
      }
    }
    QVector<size_t> eulerCompDim(1, 3);
    FloatArrayType::Pointer subEulers = FloatArrayType::CreateArray(count, eulerCompDim, "Eulers_Per_Phase");
    subEulers->initializeWithValue(std::numeric_limits<float>::signaling_NaN());
    float* eu = subEulers->getPointer(0);

    // Now loop through the eulers again and this time add them to the subEulers Array
    count = 0;
    for (size_t i = 0; i < numPoints; ++i)
    {
      if (m_CellPhases[i] == phase)
      {
        if (missingGoodVoxels == true || m_GoodVoxels[i] == true)
        {
          eu[count * 3] = m_CellEulerAngles[i * 3];
          eu[count * 3 + 1] = m_CellEulerAngles[i * 3 + 1];
          eu[count * 3 + 2] = m_CellEulerAngles[i * 3 + 2];
          count++;
        }
      }
    }
    if (subEulers->getNumberOfTuples() == 0) { continue; } // Skip because we have no Pole Figure data

    QVector<UInt8ArrayType::Pointer> figures;

    PoleFigureConfiguration_t config;
    config.eulers = subEulers.get();
    config.imageDim = getImageSize();
    config.lambertDim = getLambertSize();
    config.numColors = getNumColors();

    QString label("Phase_");
    label.append(QString::number(phase));

    QString ss = QObject::tr("Generating Pole Figures for Phase %1").arg(phase);
    notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss);

    switch(m_CrystalStructures[phase])
    {
      case Ebsd::CrystalStructure::Cubic_High:
        figures = makePoleFigures<CubicOps>(config);
        break;
      case Ebsd::CrystalStructure::Cubic_Low:
        figures = makePoleFigures<CubicLowOps>(config);
        break;
      case Ebsd::CrystalStructure::Hexagonal_High:
        figures = makePoleFigures<HexagonalOps>(config);
        break;
      case Ebsd::CrystalStructure::Hexagonal_Low:
        figures = makePoleFigures<HexagonalLowOps>(config);
        break;
      case Ebsd::CrystalStructure::Trigonal_High:
        //   figures = makePoleFigures<TrigonalOps>(config);
        notifyWarningMessage(getHumanLabel(), "Trigonal High Symmetry is not supported for Pole figures. This phase will be omitted from results", -1010);
        break;
      case Ebsd::CrystalStructure::Trigonal_Low:
        //  figures = makePoleFigures<TrigonalLowOps>(config);
        notifyWarningMessage(getHumanLabel(), "Trigonal Low Symmetry is not supported for Pole figures. This phase will be omitted from results", -1010);
        break;
      case Ebsd::CrystalStructure::Tetragonal_High:
        //  figures = makePoleFigures<TetragonalOps>(config);
        notifyWarningMessage(getHumanLabel(), "Tetragonal High Symmetry is not supported for Pole figures. This phase will be omitted from results", -1010);
        break;
      case Ebsd::CrystalStructure::Tetragonal_Low:
        //  figures = makePoleFigures<TetragonalLowOps>(config);
        notifyWarningMessage(getHumanLabel(), "Tetragonal Low Symmetry is not supported for Pole figures. This phase will be omitted from results", -1010);
        break;
      case Ebsd::CrystalStructure::OrthoRhombic:
        figures = makePoleFigures<OrthoRhombicOps>(config);
        break;
      case Ebsd::CrystalStructure::Monoclinic:
        figures = makePoleFigures<MonoclinicOps>(config);
        break;
      case Ebsd::CrystalStructure::Triclinic:
        figures = makePoleFigures<TriclinicOps>(config);
        break;
      default:
        break;

    }

    if (figures.size() == 3)
    {
      QImage combinedImage = PoleFigureImageUtilities::Create3ImagePoleFigure(figures[0].get(), figures[1].get(), figures[2].get(), config, getImageLayout());
      writeImage(combinedImage, label);
    }
  }

  /* Let the GUI know we are done with this filter */
  notifyStatusMessage(getHumanLabel(), "Complete");
}
Esempio n. 12
0
bool
PowerTapDevice::download( const QDir &tmpdir,
                         QList<DeviceDownloadFile> &files,
                         QString &err)
{
    if (!dev->open(err)) {
        err = tr("ERROR: open failed: ") + err;
        return false;
    }
    // make several attempts at reading the version
    int attempts = 3;
    int veridx = -1;
    int version_len;
    char vbuf[256];
    QByteArray version;

    do {
	if (!doWrite(dev, 0x56, false, err)) // 'V'
	    return false;

    emit updateStatus( tr("Reading version...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
	    return false;
	}

	version_len = readUntilNewline(dev, vbuf, sizeof(vbuf), err);
	if (version_len < 0) {
	    err = tr("Error reading version: ") + err;
	    return false;
	}
	if (PT_DEBUG) {
	    printf("read version \"%s\"\n",
		   cEscape(vbuf, version_len).toAscii().constData());
	}
	version = QByteArray(vbuf, version_len);

	// We expect the version string to be something like
	// "VER 02.21 PRO...", so if we see two V's, it's probably
	// because there's a hardware echo going on.
	veridx = version.indexOf("VER");

    } while ((--attempts > 0) && (veridx < 0));

    if (veridx < 0) {
	err = QString(tr("Unrecognized version \"%1\""))
	    .arg(cEscape(vbuf, version_len));
	return false;
    }
    bool hwecho = version.indexOf('V') < veridx;
    if (PT_DEBUG) printf("hwecho=%s\n", hwecho ? "true" : "false");

    emit updateStatus( tr("Reading header...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }

    if (!doWrite(dev, 0x44, hwecho, err)) // 'D'
        return false;
    unsigned char header[6];
    int header_len = dev->read(header, sizeof(header), err);
    if (header_len != 6) {
        if (header_len < 0)
            err = tr("ERROR: reading header: ") + err;
        else
            err = tr("ERROR: timeout reading header");
        return false;
    }
    if (PT_DEBUG) {
        printf("read header \"%s\"\n",
               cEscape((char*) header,
                       sizeof(header)).toAscii().constData());
    }
    QVector<unsigned char> records;
    for (size_t i = 0; i < sizeof(header); ++i)
        records.append(header[i]);

    emit updateStatus( tr("Reading ride data...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }
    double recIntSecs = 0.0;

    fflush(stdout);
    while (true) {
        if (PT_DEBUG) printf("reading block\n");
        unsigned char buf[256 * 6 + 1];
        int n = dev->read(buf, 2, err);
        if (n < 2) {
            if (n < 0)
                err = tr("ERROR: reading first two: ") + err;
            else
                err = tr("ERROR: timeout reading first two");
            return false;
        }
        if (PT_DEBUG) {
            printf("read 2 bytes: \"%s\"\n",
                   cEscape((char*) buf, 2).toAscii().constData());
        }
        if (hasNewline((char*) buf, 2))
            break;
        unsigned count = 2;
        while (count < sizeof(buf)) {
            n = dev->read(buf + count, sizeof(buf) - count, err);
            if (n < 0) {
                err = tr("ERROR: reading block: ") + err;
                return false;
            }
            if (n == 0) {
                err = tr("ERROR: timeout reading block");
                return false;
            }
            if (PT_DEBUG) {
                printf("read %d bytes: \"%s\"\n", n,
                       cEscape((char*) buf + count, n).toAscii().constData());
            }
            count += n;
        }
        unsigned csum = 0;
        for (int i = 0; i < ((int) sizeof(buf)) - 1; ++i)
            csum += buf[i];
        if ((csum % 256) != buf[sizeof(buf) - 1]) {
            err = tr("ERROR: bad checksum");
            return false;
        }
        if (PT_DEBUG) printf("good checksum\n");
        for (size_t i = 0; i < sizeof(buf) - 1; ++i)
            records.append(buf[i]);
        if (recIntSecs == 0.0) {
            unsigned char *data = records.data();
            bool bIsVer81 = PowerTapUtil::is_Ver81(data);
            for (int i = 0; i < records.size(); i += 6) {
                if (PowerTapUtil::is_config(data + i, bIsVer81)) {
                    unsigned unused1, unused2, unused3;
                    PowerTapUtil::unpack_config(
                        data + i, &unused1, &unused2,
                        &recIntSecs, &unused3, bIsVer81);
                }
            }
        }
        if (recIntSecs != 0.0) {
            int min = (int) round(records.size() / 6 * recIntSecs);
            emit updateProgress( QString(tr("progress: %1:%2"))
                .arg(min / 60)
                .arg(min % 60, 2, 10, QLatin1Char('0')));
        }
        if(m_Cancelled){
            err = tr("download cancelled");
            return false;
        }
        if (!doWrite(dev, 0x71, hwecho, err)) // 'q'
            return false;
    }

    QString tmpl = tmpdir.absoluteFilePath(".ptdl.XXXXXX");
    QTemporaryFile tmp(tmpl);
    tmp.setAutoRemove(false);
    if (!tmp.open()) {
        err = tr("Failed to create temporary file ")
            + tmpl + ": " + tmp.error();
        return false;
    }
    // QTemporaryFile initially has permissions set to 0600.
    // Make it readable by everyone.
    tmp.setPermissions(tmp.permissions()
                       | QFile::ReadOwner | QFile::ReadUser
                       | QFile::ReadGroup | QFile::ReadOther);

    DeviceDownloadFile file;
    file.extension = "raw";
    file.name = tmp.fileName();

    QTextStream os(&tmp);
    os << hex;
    os.setPadChar('0');

    bool time_set = false;
    unsigned char *data = records.data();
    bool bIsVer81 = PowerTapUtil::is_Ver81(data);

    for (int i = 0; i < records.size(); i += 6) {
        if (data[i] == 0 && !bIsVer81)
            continue;
        for (int j = 0; j < 6; ++j) {
            os.setFieldWidth(2);
            os << data[i+j];
            os.setFieldWidth(1);
            os << ((j == 5) ? "\n" : " ");
        }
        if (!time_set && PowerTapUtil::is_time(data + i, bIsVer81)) {
            struct tm time;
            time_t timet = PowerTapUtil::unpack_time(data + i, &time, bIsVer81);
            file.startTime.setTime_t( timet );
            time_set = true;
        }
    }
    if (!time_set) {
        err = tr("Failed to find ride time.");
        tmp.setAutoRemove(true);
        return false;
    }

    files << file;
    return true;
}
int
main(int argc, char *argv[])
{

    //QMultiHash<QString, StringPair> hashTable;
    QHash<QString, QSet<QString> > predictTable;
    QHash<StringPair, ulong> countTable;
    QVector<QString> tagsV;
    QHash<ulong, QVector<StringPair> > hashTb;
    tagsV.clear();
    QFile fin(argv[1]);
    QTextStream out(stdout);
    QTextStream err(stderr);

    if (argc != 3) {
        out << "Usage: genhashtable dictfile.txt hashtablefile.txt" << endl;
        return 0;
    }

    if (!fin.open(QIODevice::ReadOnly | QIODevice::Text)) {
        err << "ERROR: input file not found" << endl;
        return 1;
    }

    QTextStream sfin(&fin);
    sfin.setCodec("UTF-8");
    out.setCodec("UTF-8");
    QString line = sfin.readLine();
    QStringList lineParts;

    bool isfirst = false;

    QString form, normalForm, tags;
    while (!line.isNull()) {
        lineParts = line.split(QRegExp("[\t ]"), QString::SkipEmptyParts);
        if (isfirst) {
            if (!(lineParts.size() < 2 || lineParts[1].startsWith("VERB,") || lineParts[1].startsWith("PRTF,")
                    || lineParts[1].startsWith("PRTS,") || lineParts[1].startsWith("GRND,"))) {
                normalForm = lineParts[0];
            }
            isfirst = false;
        }

        if (lineParts.size() > 2 && lineParts[1].startsWith("INFN,")) {
            normalForm = lineParts[0];
        }

        if (lineParts.size() < 1) {
            line = sfin.readLine();
            continue;
        }

        if (lineParts.size() == 1) {
            isfirst = true;
            line = sfin.readLine();
            continue;
        }
        form = lineParts[0]; 
        QChar yo = QString::fromUtf8("Ё")[0];
        QChar ye = QString::fromUtf8("Е")[0];
        form.replace(yo, ye, Qt::CaseInsensitive);
        tags = lineParts[1];
        
        if (lineParts.size() == 3) {
            tags += ("," + lineParts[2]);
        }

        if (tagsV.indexOf(tags) == -1) {
            tagsV.append(tags);
        }
        hashTb[tagsV.indexOf(tags)].append(StringPair(normalForm, form));

        //hashTable.insert(form, StringPair(normalForm, tags));
        predictTable[form.right(3)].insert(tags);
        ++countTable[StringPair(form.right(3), tags)];

        line = sfin.readLine();
    }
    fin.close();

    //out << "Table size: " << hashTable.size() << endl;
    QString result("");
    for (int i = 0; i < tagsV.size(); ++i) {
        result += ("& " + tagsV[i] + " ");
        for (int j = 0; j < hashTb[i].size(); ++j) {
            result += (hashTb[i][j].first + " " + hashTb[i][j].second + " ");
        }
    }
    
    result += "\n----------";
    for (QHash<QString, QSet<QString> >::const_iterator itr = predictTable.begin(); itr != predictTable.end(); ++itr) {
        for (QSet<QString>::const_iterator jtr = itr.value().begin(); jtr != itr.value().end(); ++jtr) {
            result += (" " + itr.key() + " " + *jtr);
        }
    }
    result += "\n----------";
    for (QHash<StringPair, ulong>::const_iterator itr = countTable.begin(); itr != countTable.end(); ++itr) {
        result += (" " + itr.key().first + " " + itr.key().second + " " + QString::number(itr.value()));
    }
    result += "\n----------";


    QFile hashFile(argv[2]);
    hashFile.open(QIODevice::WriteOnly);
    QTextCodec *cp1251 = QTextCodec::codecForName("CP1251");
    hashFile.write(qCompress(cp1251->fromUnicode(result)));
    hashFile.flush();
    hashFile.close();

    return 0;
}
Esempio n. 14
0
double BeatUtils::calculateBpm(const QVector<double>& beats, int SampleRate,
                               int min_bpm, int max_bpm) {
    /*
     * Let's compute the average local
     * BPM for N subsequent beats.
     * The average BPMs are
     * added to a list from which the statistical
     * median is computed
     *
     * N=12 seems to work great; We coincide with Traktor's
     * BPM value in many case but not worse than +-0.2 BPM
     */
    /*
     * Just to demonstrate how you would count the beats manually
     *
     *    Beat numbers:   1  2  3  4   5  6  7  8    9
     *    Beat positions: ?  ?  ?  ?  |?  ?  ?  ?  | ?
     *
     * Usually one measures the time of N beats. One stops the timer just before
     * the (N+1)th beat begins.  The BPM is then computed by 60*N/<time needed
     * to count N beats (in seconds)>
     *
     * Although beat tracking through QM is promising, the local average BPM of
     * 4 beats varies frequently by +-2 BPM.  Somtimes there N subsequent beats
     * in the grid that are computed wrongly by QM.
     *
     * Their local BPMs can be considered as outliers which would influence the
     * BPM computation negatively. To exclude outliers, we select the median BPM
     * over a window of N subsequent beats.

     * To do this, we take the average local BPM for every N subsequent
     * beats. We then sort the averages and take the middle to find the median
     * BPM.
     */

    if (beats.size() < 2) {
        return 0;
    }

    // If we don't have enough beats for our regular approach, just divide the #
    // of beats by the duration in minutes.
    if (beats.size() <= N) {
        return 60.0 * (beats.size()-1) * SampleRate / (beats.last() - beats.first());
    }

    QMap<double, int> frequency_table;
    QList<double> average_bpm_list = computeWindowedBpmsAndFrequencyHistogram(
        beats, N, 1, SampleRate, &frequency_table);

    // Get the median BPM.
    qSort(average_bpm_list);
    const double median = computeSampleMedian(average_bpm_list);

    /*
     * Okay, let's consider the median an estimation of the BPM To not soley
     * rely on the median, we build the average weighted value of all bpm values
     * being at most +-1 BPM from the median away.  Please note, this has
     * improved the BPM: While relying on median only we may have a deviation of
     * about +-0.2 BPM, taking into account BPM values around the median leads
     * to deviation of +- 0.05 Please also note that this value refers to
     * electronic music, but to be honest, the BPM detection of Traktor and Co
     * work best with electronic music, too. But BPM detection for
     * non-electronic music isn't too bad.
     */

    //qDebug() << "BPM range between " << min_bpm << " and " << max_bpm;

    // a subset of the 'frequency_table', where the bpm values are +-1 away from
    // the median average BPM.
    QMap<double, int> filtered_bpm_frequency_table;
    const double filterWeightedAverageBpm = computeFilteredWeightedAverage(
        frequency_table, median, kBpmFilterTolerance, &filtered_bpm_frequency_table);

    if (sDebug) {
        qDebug() << "Statistical median BPM: " << median;
        qDebug() << "Weighted Avg of BPM values +- 1BPM from the media"
                 << filterWeightedAverageBpm;
    }

    /*
     * Although we have a minimal deviation of about +- 0.05 BPM units compared
     * to Traktor, this deviation may cause the beat grid to look unaligned,
     * especially at the end of a track.  Let's try to get the BPM 'perfect' :-)
     *
     * Idea: Iterate over the original beat set where some detected beats may be
     * wrong. The beat is considered 'correct' if the beat position is within
     * epsilon of a beat grid obtained by the global BPM.
     *
     * If the beat turns out correct, we can compute the error in BPM units.
     * E.g., we can check the original beat position after 60 seconds. Ideally,
     * the approached beat is just a couple of samples away, i.e., not worse
     * than 0.05 BPM units.  The distance between these two samples can be used
     * for BPM error correction.
     */

     double perfect_bpm = 0;
     double firstCorrectBeatSample = beats.first();
     bool foundFirstCorrectBeat = false;

     int counter = 0;
     int perfectBeats = 0;
     for (int i = N; i < beats.size(); i += 1) {
         // get start and end sample of the beats
         double beat_start = beats.at(i-N);
         double beat_end = beats.at(i);

         // Time needed to count a bar (N beats)
         double time = (beat_end - beat_start) / SampleRate;
         if (time == 0) continue;
         double local_bpm = 60.0 * N / time;
         // round BPM to have two decimal places
         local_bpm = floor(local_bpm * kHistogramDecimalScale + 0.5) / kHistogramDecimalScale;

         //qDebug() << "Local BPM beat " << i << ": " << local_bpm;
         if (!foundFirstCorrectBeat &&
             filtered_bpm_frequency_table.contains(local_bpm) &&
             fabs(local_bpm - filterWeightedAverageBpm) < BPM_ERROR) {
             firstCorrectBeatSample = beat_start;
             foundFirstCorrectBeat = true;
             if (sDebug) {
                 qDebug() << "Beat #" << (i - N)
                          << "is considered as reference beat with BPM:"
                          << local_bpm;
             }
         }
         if (foundFirstCorrectBeat) {
             if (counter == 0) {
                 counter = N;
             } else {
                 counter += 1;
             }
             double time2 = (beat_end - firstCorrectBeatSample) / SampleRate;
             double correctedBpm = 60 * counter / time2;

             if (fabs(correctedBpm - filterWeightedAverageBpm) <= BPM_ERROR) {
                 perfect_bpm += correctedBpm;
                 ++perfectBeats;
                 if (sDebug) {
                     qDebug() << "Beat #" << (i-N)
                              << "is considered as correct -->BPM improved to:"
                              << correctedBpm;
                 }
             }
         }
     }

     const double perfectAverageBpm = perfectBeats > 0 ?
             perfect_bpm / perfectBeats : filterWeightedAverageBpm;

     // Round values that are within BPM_ERROR of a whole number.
     const double rounded_bpm = floor(perfectAverageBpm + 0.5);
     const double bpm_diff = fabs(rounded_bpm - perfectAverageBpm);
     bool perform_rounding = (bpm_diff <= BPM_ERROR);

     // Finally, restrict the BPM to be within min_bpm and max_bpm.
     const double maybeRoundedBpm = perform_rounding ? rounded_bpm : perfectAverageBpm;
     const double constrainedBpm = constrainBpm(maybeRoundedBpm, min_bpm, max_bpm, false);

     if (sDebug) {
         qDebug() << "SampleMedianBpm=" << median;
         qDebug() << "FilterWeightedAverageBpm=" << filterWeightedAverageBpm;
         qDebug() << "Perfect BPM=" << perfectAverageBpm;
         qDebug() << "Rounded Perfect BPM=" << rounded_bpm;
         qDebug() << "Rounded difference=" << bpm_diff;
         qDebug() << "Perform rounding=" << perform_rounding;
         qDebug() << "Constrained to Range [" << min_bpm << "," << max_bpm << "]=" << constrainedBpm;
     }
     return constrainedBpm;
}
Esempio n. 15
0
QVector<QString> HMMTagger::tag(QVector<QString> const &sentence) const
{
	QVector<QVector<TagMatrixEntry> > tagMatrix(sentence.size(), QVector<TagMatrixEntry>());

	// We can't estimate the trigram probabilities for the first two tags,
	// so add them to the tag matrix as-is. Normally, these are start markers
	// anyway. XXX - maybe we should at the very least look them up in the
	// lexicon?
	size_t startTag = d_model->tagNumbers().find(sentence[0]).value();
	tagMatrix[0].push_back(TagMatrixEntry(startTag));
	tagMatrix[1].push_back(TagMatrixEntry(startTag));
	tagMatrix[1][0].probs[&tagMatrix[0][0]] = 0.0;
	tagMatrix[1][0].bps[&tagMatrix[0][0]] = 0;

	double beam = 0.0;

	// Loop through the tokens.
	for (int i = 2; i < sentence.size(); ++i)
	{
		double columnHighestProb = -numeric_limits<double>::infinity();
		WordHandler::ProbSet tagProbs = d_wordHandler->tags(sentence[i]);

		// Loop over all possible tags for the current word.
		for (WordHandler::ProbSet::const_iterator tagProbsIter = tagProbs.begin();
			tagProbsIter != tagProbs.end(); ++tagProbsIter)
		{
			TagMatrixEntry newEntry(tagProbsIter->first);

			// Loop over all possible trigrams.
			for (QVector<TagMatrixEntry>::const_iterator t2Iter =
				tagMatrix[i - 1].begin(); t2Iter != tagMatrix[i - 1].end();
				++t2Iter)
			{
				double highestProb = -numeric_limits<double>::infinity();
				TagMatrixEntry const *highestProbBp = 0;

				for (QHash<TagMatrixEntry const *, double>::const_iterator t1Iter =
					t2Iter->probs.begin(); t1Iter != t2Iter->probs.end(); ++t1Iter)
				{
					if (t1Iter.value() < beam)
						continue;

					TriGram curTriGram(t1Iter.key()->tag, t2Iter->tag, tagProbsIter->first);
					double triGramProb = d_smoothing->triGramProb(curTriGram);

					// The probability of the current state is P(w|t) * p(t3|t1,t2) *
					// p(prev_state).
					double prob = triGramProb + tagProbsIter->second + t1Iter.value();

					// Store the path the maximizes the probability.
					if (prob > highestProb)
					{
						highestProb = prob;
						//highestProbBp = t2Iter->bps.find(t1Iter->first)->second;
						highestProbBp = t1Iter.key();
					}
				}

				newEntry.probs[&(*t2Iter)] = highestProb;
				newEntry.bps[&(*t2Iter)] = highestProbBp;

				if (highestProb > columnHighestProb)
					columnHighestProb = highestProb;
			}


			tagMatrix[i].push_back(newEntry);
		}

		beam = columnHighestProb - d_beamFactor;
	}

	// Find the most probable final state.
	double highestProb = -numeric_limits<double>::infinity();
	TagMatrixEntry const *tail = 0;
	TagMatrixEntry const *beforeTail = 0;

	QVector<TagMatrixEntry> &lastColumn = tagMatrix[sentence.size() - 1];

	for (QVector<TagMatrixEntry>::const_iterator iter = lastColumn.begin();
			iter != lastColumn.end(); ++iter)
		for (QHash<TagMatrixEntry const *, double>::const_iterator probIter =
			iter->probs.begin(); probIter != iter->probs.end(); ++probIter)
		{
			if (probIter.value() > highestProb)
			{
				highestProb = probIter.value();
				tail = &(*iter);
				beforeTail = probIter.key();
			}
		}

	// Extract the most probable tag sequence.
	QVector<QString> tagSequence;
	for (int i = tagMatrix.size() - 1; i >= 0; --i)
	{
		QString tagString = d_model->numberTags().find(tail->tag).value();
		tagSequence.push_back(tagString);

		if (beforeTail)
		{
			TagMatrixEntry const *tmp = tail->bps.find(beforeTail).value();
			tail = beforeTail;
			beforeTail = tmp;
		}
	}

	// Since we have extracted the most probable tag sequence from tail to
	// head, we have to reverse it.
	reverse(tagSequence.begin(), tagSequence.end());

	return tagSequence;
}
Esempio n. 16
0
bool biggestIteratorTooBig(const QVector<Cit> &pWaveStarts,
                           const Cit &endOfSignal) {
  return any_of(begin(pWaveStarts), end(pWaveStarts), [&](const Cit &it) {
    return distance(it + averagePWave.size(), endOfSignal) < 0;
  });
}
Esempio n. 17
0
void QAlphaPaintEngine::flushAndInit(bool init)
{
    Q_D(QAlphaPaintEngine);
    Q_ASSERT(d->m_pass == 0);

    if (d->m_pic) {
        d->m_picpainter->end();

        // set clip region
        d->m_alphargn = d->m_alphargn.intersected(QRect(0, 0, d->m_pdev->width(), d->m_pdev->height()));

        // just use the bounding rect if it's a complex region..
        QVector<QRect> rects = d->m_alphargn.rects();
        if (rects.size() > 10) {
            QRect br = d->m_alphargn.boundingRect();
            d->m_alphargn = QRegion(br);
            rects.clear();
            rects.append(br);
        }

        d->m_cliprgn = d->m_alphargn;

        // now replay the QPicture
        ++d->m_pass; // we are now doing pass #2

        // reset states
        gccaps = d->m_savedcaps;

        painter()->save();
        d->resetState(painter());

        // make sure the output from QPicture is unscaled
        QTransform mtx;
        mtx.scale(1.0f / (qreal(d->m_pdev->logicalDpiX()) / qreal(qt_defaultDpiX())),
                  1.0f / (qreal(d->m_pdev->logicalDpiY()) / qreal(qt_defaultDpiY())));
        painter()->setTransform(mtx);
        painter()->drawPicture(0, 0, *d->m_pic);

        d->m_cliprgn = QRegion();
        d->resetState(painter());

        // fill in the alpha images
        for (int i=0; i<rects.size(); ++i)
            d->drawAlphaImage(rects.at(i));

        d->m_alphargn = QRegion();

        painter()->restore();

        --d->m_pass; // pass #2 finished

        cleanUp();
    }

    if (init) {
        gccaps = PaintEngineFeatures(AllFeatures & ~QPaintEngine::ObjectBoundingModeGradients);

        d->m_pic = new QPicture();
        d->m_pic->d_ptr->in_memory_only = true;
        d->m_picpainter = new QPainter(d->m_pic);
        d->m_picengine = d->m_picpainter->paintEngine();

        // When newPage() is called and the m_picpainter is recreated
        // we have to copy the current state of the original printer
        // painter back to the m_picpainter
        d->m_picpainter->setPen(painter()->pen());
        d->m_picpainter->setBrush(painter()->brush());
        d->m_picpainter->setBrushOrigin(painter()->brushOrigin());
        d->m_picpainter->setFont(painter()->font());
        d->m_picpainter->setOpacity(painter()->opacity());
        d->m_picpainter->setTransform(painter()->combinedTransform());
        d->m_picengine->syncState();
    }
}
// CalculateBoorNet - inserts new control points with de Boor algorithm for
// transformation of B-spline into composite Bezier curve.
void BezierInterpolator::CalculateBoorNet(const QVector<QPointF *> &controlPoints,
    const QVector<qreal> &knotVector,
    QPolygonF &boorNetPoints) const {
  Q_ASSERT(controlPoints.size() > 2);
  Q_ASSERT(knotVector.size() > 4);
  // We draw uniform cubic B-spline that passes through endpoints, so we assume
  // that multiplicity of first and last knot is 4 and 1 for knots between.

  QVector<qreal> newKnotVector = knotVector;
  boorNetPoints.clear();
  for (int counter = 0; counter < controlPoints.size(); ++counter)
    boorNetPoints.push_back(*controlPoints[counter]);

  // Insert every middle knot 2 times to increase its multiplicity from 1 to 3.
  const int curveDegree = 3;
  const int increaseMultiplicity = 2;

  for (int knotCounter = 4; knotCounter < newKnotVector.size() - 4;
       knotCounter += 3) {
    QHash< int, QHash<int, QPointF> > tempPoints;
    for (int counter = knotCounter - curveDegree; counter <= knotCounter;
         ++counter)
      tempPoints[counter][0] = boorNetPoints[counter];

    for (int insertCounter = 1; insertCounter <= increaseMultiplicity;
         ++insertCounter)
      for (int i = knotCounter - curveDegree + insertCounter; i < knotCounter;
           ++i) {
        double coeff = (newKnotVector[knotCounter] - newKnotVector[i]) /
            (newKnotVector[i + curveDegree - insertCounter + 1] - newKnotVector[i]);
        QPointF newPoint = (1.0 - coeff) * tempPoints[i - 1][insertCounter - 1] +
                           coeff * tempPoints[i][insertCounter - 1];
        tempPoints[i][insertCounter] = newPoint;
      }

    for (int counter = 0; counter < increaseMultiplicity; ++counter)
      newKnotVector.insert(knotCounter, newKnotVector[knotCounter]);

    // Fill new control points.
    QPolygonF newBoorNetPoints;
    for (int counter = 0; counter <= knotCounter - curveDegree; ++counter)
      newBoorNetPoints.push_back(boorNetPoints[counter]);

    for (int counter = 1; counter <= increaseMultiplicity; ++counter) {
      QPointF &newP = tempPoints[knotCounter - curveDegree + counter][counter];
      newBoorNetPoints.push_back(newP);
    }

    for (int counter = -curveDegree + increaseMultiplicity + 1; counter <= -1;
         ++counter) {
      QPointF &newP = tempPoints[knotCounter + counter][increaseMultiplicity];
      newBoorNetPoints.push_back(newP);
    }

    for (int counter = increaseMultiplicity - 1; counter >= 1; --counter)
      newBoorNetPoints.push_back(tempPoints[knotCounter - 1][counter]);

    for (int counter = knotCounter - 1; counter < boorNetPoints.size(); ++counter)
      newBoorNetPoints.push_back(boorNetPoints[counter]);

    boorNetPoints = newBoorNetPoints;
  }
}
Esempio n. 19
0
File: showfps.cpp Progetto: 8l/kwin
void ShowFpsEffect::paintGL(int fps)
{
    int x = this->x;
    int y = this->y;
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    // TODO painting first the background white and then the contents
    // means that the contents also blend with the background, I guess
    ShaderBinder binder(ShaderManager::ColorShader);
    GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer();
    vbo->reset();
    QColor color(255, 255, 255);
    color.setAlphaF(alpha);
    vbo->setColor(color);
    QVector<float> verts;
    verts.reserve(12);
    verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y;
    verts << x << y;
    verts << x << y + MAX_TIME;
    verts << x << y + MAX_TIME;
    verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y + MAX_TIME;
    verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y;
    vbo->setData(6, 2, verts.constData(), NULL);
    vbo->render(GL_TRIANGLES);
    y += MAX_TIME; // paint up from the bottom
    color.setRed(0);
    color.setGreen(0);
    vbo->setColor(color);
    verts.clear();
    verts << x + FPS_WIDTH << y - fps;
    verts << x << y - fps;
    verts << x << y;
    verts << x << y;
    verts << x + FPS_WIDTH << y;
    verts << x + FPS_WIDTH << y - fps;
    vbo->setData(6, 2, verts.constData(), NULL);
    vbo->render(GL_TRIANGLES);


    color.setBlue(0);
    vbo->setColor(color);
    QVector<float> vertices;
    for (int i = 10;
            i < MAX_TIME;
            i += 10) {
        vertices << x << y - i;
        vertices << x + FPS_WIDTH << y - i;
    }
    vbo->setData(vertices.size() / 2, 2, vertices.constData(), NULL);
    vbo->render(GL_LINES);
    x += FPS_WIDTH;

    // Paint FPS graph
    paintFPSGraph(x, y);
    x += NUM_PAINTS;

    // Paint amount of rendered pixels graph
    paintDrawSizeGraph(x, y);

    // Paint FPS numerical value
    if (fpsTextRect.isValid()) {
        fpsText.reset(new GLTexture(fpsTextImage(fps)));
        fpsText->bind();
        ShaderBinder binder(ShaderManager::SimpleShader);
        if (effects->compositingType() == OpenGL2Compositing) {
            binder.shader()->setUniform("offset", QVector2D(0, 0));
        }
        fpsText->render(QRegion(fpsTextRect), fpsTextRect);
        fpsText->unbind();
        effects->addRepaint(fpsTextRect);
    }

    // Paint paint sizes
    glDisable(GL_BLEND);
}
void
rce::gui::RImageMarkerScene::
mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    if(mouseEvent->button() == Qt::LeftButton)
    {
        const QGraphicsView *eventView = NULL;
        if(mouseEvent->widget() != NULL)
        {
            eventView = dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget());
        }

        QTransform viewTransform;
        if(eventView != NULL)
        {
            viewTransform = eventView->transform();
        }

        itemEdited_ = false;
        switch(mode_)
        {
            case rce::gui::RImageMarkerScene::DrawPointMode:
                {
                    // check if there is handle under mouse
                    QList<QGraphicsItem *> itemsUnderMouse = items(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(),
                                                                                                         mouseEvent->scenePos(),
                                                                                                         dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())),
                                                                   Qt::IntersectsItemBoundingRect,
                                                                   Qt::DescendingOrder,
                                                                   viewTransform);
                    QGraphicsItem *handle = NULL;
                    for(int i = 0; i < itemsUnderMouse.size(); ++i)
                    {
                        if((itemsUnderMouse[i]->data(RCE_ITEM_TYPE_DATA_INDEX).toUInt() == HandleType)
                           && itemsUnderMouse[i]->boundingRect().contains(itemsUnderMouse[i]->mapFromScene(mouseEvent->scenePos())))
                        {
                            handle = itemsUnderMouse[i];
                            break;
                        }
                    }

                    if(handle != NULL)
                    { // there is handle, set is as active
                        activeHandleIdx_ = 0;
                    }
                    else
                    {
                        activeHandleIdx_ = -1;
                    }
                }
                break;
            case rce::gui::RImageMarkerScene::DrawPolygonMode:
            case rce::gui::RImageMarkerScene::DrawPolylineMode:
                {
                    // check if there is handle under mouse
                    QList<QGraphicsItem *> itemsUnderMouse = items(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(),
                                                                                                         mouseEvent->scenePos(),
                                                                                                         dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())),
                                                                   Qt::IntersectsItemBoundingRect,
                                                                   Qt::DescendingOrder,
                                                                   viewTransform);
                    QGraphicsItem *handle = NULL;
                    for(int i = 0; i < itemsUnderMouse.size(); ++i)
                    {
                        if((itemsUnderMouse[i]->data(RCE_ITEM_TYPE_DATA_INDEX).toUInt() == HandleType)
                           && itemsUnderMouse[i]->boundingRect().contains(itemsUnderMouse[i]->mapFromScene(mouseEvent->scenePos())))
                        {
                            handle = itemsUnderMouse[i];
                            break;
                        }
                    }

                    if(handle != NULL)
                    { // there is handle, set is as active
                        activeHandleIdx_ = handle->data(RCE_ITEM_ID_DATA_INDEX).toInt();
                    }
                    else
                    { // there is not handle - create new
                        addControlPoint(mouseEvent->scenePos());
                        itemEdited_ = true;
                        activeHandleIdx_ = handles_.size() - 1;
                    }
                }
                break;
            case rce::gui::RImageMarkerScene::PickPolygonMode:
            case rce::gui::RImageMarkerScene::PickPolylineMode:
            case rce::gui::RImageMarkerScene::PickPointMode:
            case rce::gui::RImageMarkerScene::PickAnyMode:
                {
                    QVector<quint32> polygons;
                    QVector<quint32> polylines;
                    QVector<quint32> points;

                    getItemsAtPosition(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(),
                                                                             mouseEvent->scenePos(),
                                                                             dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())),
                                       polygons,
                                       polylines,
                                       points,
                                       viewTransform);

                    if(polygons.size() + polylines.size() + points.size() > 1)
                    { // show menu

                        QMap<QAction *, quint32> actionToPolygon;
                        QMap<QAction *, quint32> actionToPolyline;
                        QMap<QAction *, quint32> actionToPoint;


                        QMenu *ctxMenu = new QMenu(mouseEvent->widget());
                        ctxMenu->setTitle(tr("Pick Item..."));

                        foreach(quint32 polygonID,
                                polygons)
                        {
                            actionToPolygon[ctxMenu->addAction(getPolygonDisplayName(polygonID))] = polygonID;
                        }
                        ctxMenu->addSeparator();

                        foreach(quint32 polylineID,
                                polylines)
                        {
                            actionToPolyline[ctxMenu->addAction(getPolylineDisplayName(polylineID))] = polylineID;
                        }
                        ctxMenu->addSeparator();

                        foreach(quint32 pointID,
                                points)
                        {
                            actionToPoint[ctxMenu->addAction(getPointDisplayName(pointID))] = pointID;
                        }


                        QAction *selectedAction = ctxMenu->exec(mouseEvent->screenPos());

                        if(actionToPolygon.contains(selectedAction))
                        {
                            pickedItem_ = polygonItems_[actionToPolygon[selectedAction]];
                            emit pickedPolygon(actionToPolygon[selectedAction]);
                        }
                        else if(actionToPolyline.contains(selectedAction))
                        {
                            pickedItem_ = polylineItems_[actionToPolyline[selectedAction]];
                            emit pickedPolyline(actionToPolyline[selectedAction]);
                        }
                        else if(actionToPoint.contains(selectedAction))
                        {
                            pickedItem_ = pointItems_[actionToPoint[selectedAction]];
                            emit pickedPoint(actionToPoint[selectedAction]);
                        }
                        else
                        {
                            pickedItem_ = NULL;
                            emit pickedNothing();
                        }

                        ctxMenu->deleteLater();
                    }
                    else
                    {
                        if(polygons.size() == 1)
                        {
                            pickedItem_ = polygonItems_[polygons[0]];
                            emit pickedPolygon(polygons[0]);
                        }
                        else if(polylines.size() == 1)
                        {
                            pickedItem_ = polylineItems_[polylines[0]];
                            emit pickedPolyline(polylines[0]);
                        }
                        else if(points.size() == 1)
                        {
                            pickedItem_ = pointItems_[points[0]];
                            emit pickedPoint(points[0]);
                        }
                        else
                        {
                            pickedItem_ = NULL;
                            emit pickedNothing();
                        }
                    }
                }
                break;
        }
Esempio n. 21
0
int BarPlot::plotGrant()
{
	string dataType = Node->getFirst();
	// Get the types
	// Note the type is not always going to be the within the children of the node (depending on what node is passed)
	// It will be possible to pass in a different node (say a publication type node) when implemented
	vector<node*> types;
	
	vector<node*>* temptypes = Node->getChildren();
	for (int i = 0; i < temptypes->size(); i++){
		if (temptypes->at(i)->getSecond() > 0)
			types.push_back(temptypes->at(i));
	}

	// Grab Data and prepare x axis with (professor Name) labels:
	QVector<QString> labels;
	//display the types only
	for (int i = 0; i < Node->getChildren()->size(); i++)
		labels.push_back(QString::fromStdString(Node->getChildren()->at(i)->getFirst()));


	// stacked bar chart can get cluttered, ensure no more than 30 different types
	// determine which types to push into an "Others" group
	vector<int> othersNdx;
	if (types.size() > COUNT_MAX){
		vector<double> typeSumCounts;
		for (int i = 0; i < types.size(); i++){
			typeSumCounts.push_back(types.at(i)->getFourth());
		}
		while (types.size() - othersNdx.size() > COUNT_MAX){
			othersNdx.push_back(min_element(typeSumCounts.begin(), typeSumCounts.end()) - typeSumCounts.begin());
			typeSumCounts.at(min_element(typeSumCounts.begin(), typeSumCounts.end()) - typeSumCounts.begin()) = std::numeric_limits<double>::infinity();
		}
	}

	QVector<double> ticks;
	for (int i = 1; i <= labels.size(); i++)
		ticks.push_back(i);

	QVector<double> count(labels.size());
	double *data = count.data();
	// create a new plottable area for each type, group everything within the "Others" group together
	for (int i = 0; i < types.size(); i++){
		data[i] = types.at(i)->getFourth();
	}

	QCPBars *bar = new QCPBars(this->xAxis, this->yAxis);
	bar->setName(QString::fromStdString(dataType));
	bar->setData(ticks, count);
	this->addPlottable(bar);

	// set the colors
	QPen pen;
	pen.setWidthF(1.2);
	int C_HUE = 0;
	QColor color_brush, color_pen;
	color_brush.setHsv(C_HUE, BAR_SAT, BAR_VAL);
	color_brush.setAlpha(BAR_ALPHA);
	color_pen.setHsv(C_HUE, BAR_SAT + 30, BAR_VAL + 10);
	color_pen.setAlpha(255);
	pen.setColor(color_pen);
	bar->setPen(pen);
	bar->setBrush(color_brush);

	// prepare x axis:
	this->xAxis->setAutoTicks(false);
	this->xAxis->setAutoTickLabels(false);
	this->xAxis->setTickVector(ticks);
	this->xAxis->setTickVectorLabels(labels);
	this->xAxis->setTickLabelRotation(60);
	this->xAxis->setSubTickCount(0);
	this->xAxis->setTickLength(0, 3);
	this->xAxis->grid()->setVisible(true);

	// prepare y axis:
	this->yAxis->setTickStep(5);
	this->yAxis->setPadding(5); // a bit more space to the left border
	this->yAxis->setLabel("Amount ($)");
	this->yAxis->grid()->setSubGridVisible(true);
	QPen gridPen;
	gridPen.setStyle(Qt::SolidLine);
	gridPen.setColor(QColor(0, 0, 0, 25));
	this->yAxis->grid()->setPen(gridPen);
	gridPen.setStyle(Qt::DotLine);
	this->yAxis->grid()->setSubGridPen(gridPen);
	this->yAxis->scaleRange(1.3, this->yAxis->range().center());

	this->rescaleAxes(true);
	this->xAxis->setRange(0.5, 10.5);

	// setup legend:
	QCPLayoutGrid *subLayout = new QCPLayoutGrid;
	QCPLayoutElement *dummyElement = new QCPLayoutElement;

	this->plotLayout()->addElement(0, 1, subLayout); // add sub-layout in the cell to the right of the main axis rect
	subLayout->addElement(0, 0, this->legend); // add legend
	subLayout->addElement(1, 0, dummyElement); // add dummy element below legend
	subLayout->setRowStretchFactor(0, 0.01); // make legend cell (in row 0) take up as little vertical space as possible
	this->plotLayout()->setColumnStretchFactor(1, 0.01); // make the legend cell and dummy element column as small as possible

	this->legend->setVisible(true);
	this->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight);
	this->legend->setBrush(QColor(255, 255, 255, 200));
	QPen legendPen;
	legendPen.setColor(QColor(130, 130, 130, 200));
	this->legend->setBorderPen(legendPen);
	QFont legendFont = font();
	legendFont.setPointSize(8);
	this->legend->setFont(legendFont);
	this->legend->setSelectableParts(QCPLegend::spItems); // legend box shall not be selectable, only legend items

	this->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables | QCP::iSelectLegend);
		return 0;
}
Esempio n. 22
0
int main(int argc, char **argv)
{
    //serializeUnserializeTest();
    srand(time(NULL));
    QGuiApplication app(argc, argv);
    
    QSurfaceFormat format;
    format.setSamples(16);
    
    paramCamera* c=new paramCamera();
    
    QTimer* calendar = new QTimer;

    //Add ressources
    PlyMeshReader plyReader;


    QString spring(":/springtree.ply");QString sp_name("SpringTree");
    QString summer(":/summertree.ply");QString su_name("SummerTree");
    QString autumn(":/autumntree.ply");QString au_name("AutumnTree");
    QString winter(":/wintertree.ply");QString wi_name("WinterTree");
    AssetManager::getInstance().loadMesh(sp_name,&plyReader,spring);
    AssetManager::getInstance().loadMesh(su_name,&plyReader,summer);
    AssetManager::getInstance().loadMesh(au_name,&plyReader,autumn);
    AssetManager::getInstance().loadMesh(wi_name,&plyReader,winter);

    QVector<GameWindow*> window;

    //if big file set content
    if(FileManager::getInstance().haveBigFile()) {
        qDebug() << "Saved GameWindow";
        window = FileManager::getInstance().load();
        qDebug() << "after load"<< window.size();
    }
    else {
        //Default four
        qDebug() << "Default GameWindow";
        for(int i = 0; i < 4; i++)
        {
            if (i == 0)
                window.append(new GameWindow());
            else
                window.append(new GameWindow(30));
            Terrain* terrain = new Terrain();
            terrain->loadHeightmap(":/heightmap-1.png");
            window.at(i)->setSeason(i);
            window.at(i)->setTerrain(terrain);
            window.at(i)->c = c;
        }

    }

    for(int i=0; i<window.size(); ++i) {
        qDebug() << "t-"<<i;
        FileManager::getInstance().link(window[i]);
        window[i]->setFormat(format);
        window[i]->resize(500,375);
        int x = i%2;
        int y = i>>1;

        window[i]->setPosition(x*500,y*450);
        window[i]->show();
        calendar->connect(calendar, SIGNAL(timeout()),window[i], SLOT(updateSeason()));
    }
    
    calendar->start(20);

    int appResult = app.exec();
    //AssetManager::getInstance().purge();
    return appResult;
}
Esempio n. 23
0
GeoDataLineString* MonavRunnerPrivate::retrieveRoute( const RouteRequest *route, QVector<GeoDataPlacemark*> *instructions ) const
{
    GeoDataLineString* geometry = new GeoDataLineString;
    RoutingResult reply;
    if ( retrieveData( route, &reply ) ) {
        /** @todo: make use of reply.seconds, the estimated travel time */
        for ( int i = 0; i < reply.pathNodes.size(); ++i ) {
            qreal lon = reply.pathNodes[i].longitude;
            qreal lat = reply.pathNodes[i].latitude;
            GeoDataCoordinates coordinates( lon, lat, 0, GeoDataCoordinates::Degree );
            geometry->append( coordinates );
        }

        RoutingWaypoints waypoints;
        int k = 0;
        for ( int i = 0; i < reply.pathEdges.size(); ++i ) {
            QString road = reply.nameStrings[reply.pathEdges[i].name];
            QString type = reply.typeStrings[reply.pathEdges[i].type];
            RoutingWaypoint::JunctionType junction = RoutingWaypoint::Other;
            if ( type == "roundabout" && reply.pathEdges[i].branchingPossible ) {
                junction = RoutingWaypoint::Roundabout;
            }
            for ( unsigned int l = 0; l < reply.pathEdges[i].length; ++k, ++l ) {
                qreal lon = reply.pathNodes[k].longitude;
                qreal lat = reply.pathNodes[k].latitude;
                RoutingPoint point( lon, lat );
                bool const last = l == reply.pathEdges[i].length - 1;
                RoutingWaypoint::JunctionType finalJunction = last ? junction : ( reply.pathEdges[i].branchingPossible ? RoutingWaypoint::Other : RoutingWaypoint::None );
                RoutingWaypoint waypoint( point, finalJunction, "", type, -1, road );
                waypoints.push_back( waypoint );
            }
        }

        RoutingInstructions directions = InstructionTransformation::process( waypoints );
        for ( int i = 0; i < directions.size(); ++i ) {
            GeoDataPlacemark* placemark = new GeoDataPlacemark( directions[i].instructionText() );
            GeoDataExtendedData extendedData;
            GeoDataData turnType;
            turnType.setName( "turnType" );
            turnType.setValue( qVariantFromValue<int>( int( directions[i].turnType() ) ) );
            extendedData.addValue( turnType );
            GeoDataData roadName;
            roadName.setName( "roadName" );
            roadName.setValue( directions[i].roadName() );
            extendedData.addValue( roadName );
            placemark->setExtendedData( extendedData );
            Q_ASSERT( !directions[i].points().isEmpty() );
            GeoDataLineString* geometry = new GeoDataLineString;
            QVector<RoutingWaypoint> items = directions[i].points();
            for ( int j = 0; j < items.size(); ++j ) {
                RoutingPoint point = items[j].point();
                GeoDataCoordinates coordinates( point.lon(), point.lat(), 0.0, GeoDataCoordinates::Degree );
                geometry->append( coordinates );
            }
            placemark->setGeometry( geometry );
            instructions->push_back( placemark );
        }
    }

    return geometry;
}
Esempio n. 24
0
tst_Suite::tst_Suite()
{
    testsDir = QDir(SRCDIR);
    bool testsFound = testsDir.cd("tests");
    if (!testsFound) {
        qWarning("*** no tests/ dir!");
    } else {
        if (!testsDir.exists("mjsunit.js"))
            qWarning("*** no tests/mjsunit.js file!");
        else {
            mjsunitContents = readFile(testsDir.absoluteFilePath("mjsunit.js"));
            if (mjsunitContents.isEmpty())
                qWarning("*** tests/mjsunit.js is empty!");
        }
    }
    QString willFixInNextReleaseMessage = QString::fromLatin1("Will fix in next release");
    addExpectedFailure("arguments-enum", "2", "0", willFixInNextReleaseMessage);
    addExpectedFailure("const-redecl", "undefined", "TypeError", willFixInNextReleaseMessage);
    addExpectedFailure("global-const-var-conflicts", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("string-lastindexof", "0", "-1", "test is wrong?");

    addTestExclusion("debug-*", "not applicable");
    addTestExclusion("mirror-*", "not applicable");

    addTestExclusion("array-concat", "Hangs on JSC backend");
    addTestExclusion("array-splice", "Hangs on JSC backend");
    addTestExclusion("sparse-array-reverse", "Hangs on JSC backend");

    addTestExclusion("string-case", "V8-specific behavior? (Doesn't pass on SpiderMonkey either)");

#ifdef Q_OS_WINCE
    addTestExclusion("deep-recursion", "Demands too much memory on WinCE");
    addTestExclusion("nested-repetition-count-overflow", "Demands too much memory on WinCE");
    addTestExclusion("unicode-test", "Demands too much memory on WinCE");
    addTestExclusion("mul-exhaustive", "Demands too much memory on WinCE");
#endif

#ifdef Q_OS_SYMBIAN
    addTestExclusion("nested-repetition-count-overflow", "Demands too much memory on Symbian");
    addTestExclusion("unicode-test", "Demands too much memory on Symbian");
#endif
    // Failures due to switch to JSC as back-end
    addExpectedFailure("date-parse", "NaN", "946713600000", willFixInNextReleaseMessage);
    addExpectedFailure("delete-global-properties", "true", "false", willFixInNextReleaseMessage);
    addExpectedFailure("delete", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("function-arguments-null", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("function-caller", "null", "function eval() {\n    [native code]\n}", willFixInNextReleaseMessage);
    addExpectedFailure("function-prototype", "prototype", "disconnectconnect", willFixInNextReleaseMessage);
    addExpectedFailure("number-tostring", "0", "0.0000a7c5ac471b4788", willFixInNextReleaseMessage);
    addExpectedFailure("parse-int-float", "1e+21", "1", willFixInNextReleaseMessage);
    addExpectedFailure("regexp", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("smi-negative-zero", "-Infinity", "Infinity", willFixInNextReleaseMessage);
    addExpectedFailure("string-split", "4", "3", willFixInNextReleaseMessage);
    addExpectedFailure("substr", "abcdefghijklmn", "", willFixInNextReleaseMessage);

    static const char klass[] = "tst_QScriptV8TestSuite";

    QVector<uint> *data = qt_meta_data_tst_Suite();
    // content:
    *data << 1 // revision
          << 0 // classname
          << 0 << 0 // classinfo
          << 0 << 10 // methods (backpatched later)
          << 0 << 0 // properties
          << 0 << 0 // enums/sets
          ;

    QVector<char> *stringdata = qt_meta_stringdata_tst_Suite();
    appendCString(stringdata, klass);
    appendCString(stringdata, "");

    QFileInfoList testFileInfos;
    if (testsFound)
        testFileInfos = testsDir.entryInfoList(QStringList() << "*.js", QDir::Files);
    foreach (QFileInfo tfi, testFileInfos) {
        QString name = tfi.baseName();
        // slot: signature, parameters, type, tag, flags
        QString slot = QString::fromLatin1("%0()").arg(name);
        static const int nullbyte = sizeof(klass);
        *data << stringdata->size() << nullbyte << nullbyte << nullbyte << 0x08;
        appendCString(stringdata, slot.toLatin1());
        testNames.append(name);
    }
Esempio n. 25
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    if (a.arguments().size() < 3) {
        qCritical() << "this application requires more arguments!";
        return -1;
    }

    const QString trainDirName = a.arguments().at(1);
    const QString testDirName = a.arguments().at(2);
    const QString outputName = a.arguments().at(3);
    const QString extractorName = a.arguments().at(4);
    const QStringList extractorArgs = a.arguments().mid(5);
    ExtractorInterface *extractor =
            ExtractorFactory::getExtractor(extractorName, extractorArgs);
    if (extractor == NULL) {
        qCritical() << "failed to initialise extractor" << extractorName;
        return -2;
    }

    QDir trainDir(trainDirName);
    QStringList subdirs = QStringList() << "wood" << "straw" << "salt" << "linen";
    QList<quint8> labels = QList<quint8>() << 32 << 96 << 160 << 224;
    QVector<LabelledData> trainData;
#ifdef HAS_ELAPSED_TIMER
    QElapsedTimer extractionTimer;
#else
    QTime extractionTimer;
#endif

    int threadCount = 1;
#ifdef _OPENMP
#pragma omp parallel
    {
#pragma omp single
        {
            threadCount = omp_get_num_threads();
        }
    }
#endif
    qDebug() << "using" << threadCount << "threads.";

    extractionTimer.start();
    unsigned int imagesCount = 0;
    for (int j = 0; j < subdirs.size(); j++) {
        trainDir.cd(subdirs.at(j));
        const QFileInfoList fileList = trainDir.entryInfoList(QStringList() << "*.png");
#ifdef HAS_ELAPSED_TIMER
        QElapsedTimer extractorTimer;
#else
        QTime extractorTimer;
#endif
        extractorTimer.start();
        for (int i = 0; i < fileList.size(); i++) {
            imagesCount++;
            const QString filename = fileList.at(i).filePath();
            const QImage image(filename);
            if (image.format() != QImage::Format_Indexed8) {
                qCritical("Image is not greyscale!");
                return -1;
            }
            extractor->preprocess(image);
            if (extractor->extracts()) {
                unsigned int count = trainData.size();
                trainData.resize(trainData.size() + image.width() * image.height());
                LabelledData *trainDataPtr = trainData.data();
#pragma omp parallel for
                for (int x = 0; x < image.width(); x++) {
                    for (int y = 0; y < image.height(); y++) {
                        const QVector<nnreal> res = extractor->extract(image, x, y);
                        Q_ASSERT(res.size() == extractor->size());
                        LabelledData li(res, labels.at(j));
                        const unsigned int idx = count + x * image.height() + y;
                        trainDataPtr[idx] = li;
                    }
                }
            }
            const QVector<QVector<nnreal> > ppFeatures = extractor->postprocess(image);
            const int ppCount = ppFeatures.size();
            if (ppCount > 0) {
                const int count = trainData.size();
                trainData.resize(trainData.size() + ppFeatures.size());
                LabelledData *trainDataPtr = trainData.data();
#pragma omp parallel for
                for (int k = 0; k < ppCount; k++) {
                    Q_ASSERT(ppFeatures.at(k).size() == extractor->size());
                    LabelledData ld(ppFeatures.at(k), labels.at(j));
                    trainDataPtr[count + k] = ld;
                }
            }
            qDebug() << fileList.at(i).filePath() << extractorTimer.restart();
        }
        trainDir.cdUp();
    }

    const int msecs = extractionTimer.elapsed();
    qDebug() << "trainSize:" << trainData.size() << "extraction of "
             << imagesCount << "images took" << msecs << "msecs, average"
             << float(msecs) / imagesCount << "msecs per image";
    const QString trainOutFilename(outputName + "_" + extractorName + "_train.out");
    QFile trainOutput(trainOutFilename);
    if (!trainOutput.open(QIODevice::WriteOnly)) {
        qCritical() << "failed to open output file" << trainOutFilename;
        return -3;
    }
    {
#ifdef HAS_ELAPSED_TIMER
        QElapsedTimer saveTimer;
#else
        QTime saveTimer;
#endif
        saveTimer.start();
        QDataStream outstream(&trainOutput);
        saveFeatures(outstream, extractorName, extractorArgs, extractor->size(), trainData);
        int msecs = saveTimer.elapsed();
        qDebug() << "saving took" << msecs << "msecs";
    }
    trainOutput.close();
    trainData.clear();

    {
        QDir testDir(testDirName);
        const QFileInfoList dataFileList  = testDir.entryInfoList(QStringList() << "test*.png");
        const QFileInfoList labelFileList = testDir.entryInfoList(QStringList() << "label*.png");
        Q_ASSERT(dataFileList.size() == labelFileList.size());
#ifdef HAS_ELAPSED_TIMER
        QElapsedTimer extractorTimer;
#else
        QTime extractorTimer;
#endif
        extractorTimer.start();
        QTextStream out(stdout);
        for (int i = 0; i < dataFileList.size(); i++) {
            const QImage dataImage(dataFileList.at(i).filePath());
            const QImage labelImage(labelFileList.at(i).filePath());
            QVector<LabelledData> testData;
            extractor->preprocessTest(dataImage, labelImage);
            int cnt = 0;
            if (extractor->extracts()) {
                unsigned int count = testData.size();
                testData.resize(dataImage.width() * dataImage.height());
                LabelledData *testDataPtr = testData.data();
#pragma omp parallel for
                for (int x = 0; x < dataImage.width(); x++) {
#pragma omp critical
                    {
                        cnt++;
                        out << cnt * 100 / dataImage.width() << "%" << '\r';
                        out.flush();
                    }
                    for (int y = 0; y < dataImage.height(); y++) {
                        const QVector<nnreal> res = extractor->extract(dataImage, x, y);
                        const quint8 c = labelImage.pixelIndex(x, y);
                        LabelledData li(res, c);
                        li.squeeze();
                        const unsigned int idx = count + x * dataImage.height() + y;
                        testDataPtr[idx] = li;
                    }
                }
                out << endl;
            }
            const QVector<LabelledData> ppFeatures = extractor->postprocessTest(dataImage, labelImage);
            testData << ppFeatures;
            qDebug() << dataFileList.at(i).filePath() << extractorTimer.restart();
            const QString testOutFilename(outputName + "_" + extractorName + "_test" + QString::number(i) + ".out");
            QFile testOutput(testOutFilename);
            if (!testOutput.open(QIODevice::WriteOnly)) {
                qCritical() << "failed to open output file" << testOutFilename;
                return -3;
            }
            {
#ifdef HAS_ELAPSED_TIMER
                QElapsedTimer saveTimer;
#else
                QTime saveTimer;
#endif
                saveTimer.start();
                QDataStream outstream(&testOutput);
                saveFeatures(outstream, extractorName, extractorArgs, extractor->size(), testData);
                int msecs = saveTimer.elapsed();
                qDebug() << "saving took" << msecs << "msecs";
            }
            testOutput.close();
        }
    }

    delete extractor;

    return 0;
}
Esempio n. 26
0
/** Returns a list of points on the bandwidth graph based on the supplied set
 * of rsdht or alldht values. */
void RSGraphWidget::pointsFromData(const std::vector<QPointF>& values,QVector<QPointF>& points)
{
    points.clear();

    int x = _rec.width();
    int y = _rec.height();

    float time_step = 1.0f ;	// number of seconds per pixel

    /* Translate all data points to points on the graph frame */

    // take 0 as the origin, otherwise the different curves are not aligned properly
    float last = 0;//values.back().x();

    //std::cerr << "Got " << values.size() << " values for index 0" << std::endl;

    float FS = QFontMetricsF(font()).height();
    float fact = FS/14.0 ;

    float last_px = SCALE_WIDTH*fact ;
    float last_py = 0.0f ;

 //   float min_x_no_data_threshold = 1.5 ; // 1.5 sec.

    for (uint i = 0; i < values.size(); ++i)
	 {
		 //std::cerr << "Value: (" << values[i].x() << " , " << values[i].y() << ")" << std::endl;

		 // compute point in pixels

		 qreal px = x - (values[i].x()-last)*_time_scale ;
		 qreal py = y -  valueToPixels(values[i].y()) ;

         if(px >= SCALE_WIDTH*fact && last_px < SCALE_WIDTH*fact)
		 {
             float alpha = (SCALE_WIDTH*fact - last_px)/(px - last_px) ;
             float ipx = SCALE_WIDTH*fact ;
			 float ipy = (1-alpha)*last_py + alpha*py ;

			 points << QPointF(ipx,y) ;
			 points << QPointF(ipx,ipy) ;
		 }
		 else if(i==0)
         {
             if(px < SCALE_WIDTH*fact)
			 points << QPointF(SCALE_WIDTH*fact,py) ;
             else
			 points << QPointF(px,y) ;
         }

         if(px < SCALE_WIDTH*fact)
			 continue ;

		 _maxValue = std::max(_maxValue,values[i].y()) ;

		 // remove midle point when 3 consecutive points have the same value.

		 if(points.size() > 1 && points[points.size()-2].y() == points.back().y() && points.back().y() == py)
			 points.pop_back() ;

//         	if(fabs(px - last_px)/_time_scale > min_x_no_data_threshold)
//            {
//                points << QPointF(last_px,y) ;
//                points << QPointF(px,y) ;
//            }

		 points << QPointF(px,py) ;

		 if(i==values.size()-1)
			 points << QPointF(px,y) ;

		 last_px = px ;
		 last_py = py ;

	 }
}
Esempio n. 27
0
bool QgsMapToolLabel::rotationPoint( QgsPoint& pos, bool ignoreUpsideDown, bool rotatingUnpinned )
{
  QVector<QgsPoint> cornerPoints = mCurrentLabelPos.cornerPoints;
  if ( cornerPoints.size() < 4 )
  {
    return false;
  }

  if ( mCurrentLabelPos.upsideDown && !ignoreUpsideDown )
  {
    pos = cornerPoints.at( 2 );
  }
  else
  {
    pos = cornerPoints.at( 0 );
  }

  //alignment always center/center and rotation 0 for diagrams
  if ( mCurrentLabelPos.isDiagram )
  {
    pos.setX( pos.x() + mCurrentLabelPos.labelRect.width() / 2.0 );
    pos.setY( pos.y() + mCurrentLabelPos.labelRect.height() / 2.0 );
    return true;
  }

  //adapt pos depending on data defined alignment
  QString haliString, valiString;
  currentAlignment( haliString, valiString );

  // rotate unpinned labels (i.e. no hali/vali settings) as if hali/vali was Center/Half
  if ( rotatingUnpinned )
  {
    haliString = "Center";
    valiString = "Half";
  }

//  QFont labelFont = labelFontCurrentFeature();
  QFontMetricsF labelFontMetrics( mCurrentLabelPos.labelFont );

  // NOTE: this assumes the label corner points comprise a rectangle and that the
  //       CRS supports equidistant measurements to accurately determine hypotenuse
  QgsPoint cp_0 = cornerPoints.at( 0 );
  QgsPoint cp_1 = cornerPoints.at( 1 );
  QgsPoint cp_3 = cornerPoints.at( 3 );
  //  QgsDebugMsg( QString( "cp_0: x=%1, y=%2" ).arg( cp_0.x() ).arg( cp_0.y() ) );
  //  QgsDebugMsg( QString( "cp_1: x=%1, y=%2" ).arg( cp_1.x() ).arg( cp_1.y() ) );
  //  QgsDebugMsg( QString( "cp_3: x=%1, y=%2" ).arg( cp_3.x() ).arg( cp_3.y() ) );
  double labelSizeX = qSqrt( cp_0.sqrDist( cp_1 ) );
  double labelSizeY = qSqrt( cp_0.sqrDist( cp_3 ) );

  double xdiff = 0;
  double ydiff = 0;

  if ( haliString.compare( "Center", Qt::CaseInsensitive ) == 0 )
  {
    xdiff = labelSizeX / 2.0;
  }
  else if ( haliString.compare( "Right", Qt::CaseInsensitive ) == 0 )
  {
    xdiff = labelSizeX;
  }

  if ( valiString.compare( "Top", Qt::CaseInsensitive ) == 0 || valiString.compare( "Cap", Qt::CaseInsensitive ) == 0 )
  {
    ydiff = labelSizeY;
  }
  else
  {
    double descentRatio = 1 / labelFontMetrics.ascent() / labelFontMetrics.height();
    if ( valiString.compare( "Base", Qt::CaseInsensitive ) == 0 )
    {
      ydiff = labelSizeY * descentRatio;
    }
    else if ( valiString.compare( "Half", Qt::CaseInsensitive ) == 0 )
    {
      ydiff = labelSizeY * 0.5 * ( 1 - descentRatio );
    }
  }

  double angle = mCurrentLabelPos.rotation;
  double xd = xdiff * cos( angle ) - ydiff * sin( angle );
  double yd = xdiff * sin( angle ) + ydiff * cos( angle );
  if ( mCurrentLabelPos.upsideDown && !ignoreUpsideDown )
  {
    pos.setX( pos.x() - xd );
    pos.setY( pos.y() - yd );
  }
  else
  {
    pos.setX( pos.x() + xd );
    pos.setY( pos.y() + yd );
  }
  return true;
}
Esempio n. 28
0
void FourierDCT::test()
{
	QVector<Complex> c;
	// http://www.hydrogenaudio.org/forums/index.php?showtopic=39574
	qDebug() << "FourierDCT test. expected values: 5.0000   -2.2304         0   -0.1585";
	c << Complex(1, 0);
	c << Complex(2, 0);
	c << Complex(3, 0);
	c << Complex(4, 0);
	qDebug() << "input: " << c;


	mAlphaDC = 1.0 / sqrt(c.count());
	mAlphaAC = sqrt(2.0 / c.count());
	prepareScale(c.size());
	qDebug() << mScale;


	ComplexArray *ca = new ComplexArray(boost::extents[2][1][c.count()]);
	for (int i = 0; i < c.count(); i += 1) {
		(*ca)[0][0][i] = Complex(c.at(i).real(), 0);
	}
	oneDFftV(ca, 0, 2, 1, false);

	mAlphaDC = 1.0 / sqrt(c.count());
	mAlphaAC = sqrt(2.0 / c.count());
	prepareScale(c.size());

	rearrangeDct(c);
	rearrange(c);
	transform(c, false);
	qDebug() << "transformed by hand: " << c;


	for (int i = 0; i < c.count(); i++) {
		c[i] *= mScale.at(i) * alpha(i);
	}
	qDebug() << "scaled by hand: " << c;
	for (int i = 0; i < c.size(); i++) {
		Complex g = c.at(i) * mScale.at(i) * alpha(i);
		//qDebug() << g;
		Complex x = c.at(i) * mScale.at(i);
		x *= alpha(i);
		//qDebug() << x;
		Complex x2 = c.at(i) * alpha(i);
		x2 *= mScale.at(i);
		//qDebug() << x2;
		QVector<Complex> www;
		www << g;
		www << x;
		www << x2;
		qDebug() << www;
	}

	for (int i = 0; i < c.count(); i++) {
		c[i] /= mScale.at(i) * alpha(i);
	}
	qDebug() << "divided by hand: " << c;
	for (int i = 0; i < c.size(); i++) {
		c[i].setImaginary(0);
	}
	rearrange(c);
	transform(c, true);
	qDebug() << "inverted by hand: " << c;

	c.resize(0);
	for (unsigned int i = 0; i < ca->shape()[2]; i++) {
		c << (*ca)[0][0][i];
	}
	qDebug() << "transformed automatically: " << c;

	c.resize(0);
	prepareFftV(ca, 0, 2, 1);
	for (unsigned int i = 0; i < ca->shape()[2]; i++) {
		c << (*ca)[0][0][i];
	}
	qDebug() << "scaled automatically: " << c;

	//perform(ca, true);
	oneDFftV(ca, 0, 2, 1, true);
	c.resize(0);
	for (unsigned int i = 0; i < ca->shape()[2]; i++) {
		c << (*ca)[1][0][i];
	}
	qDebug() << "inverted automatically: " << c;

	delete ca;
}
Esempio n. 29
0
void QmitkImageStatisticsView::OnClipboardStatisticsButtonClicked()
{
  QLocale tempLocal;
  QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
  if ( m_CurrentStatisticsValid && !( m_SelectedPlanarFigure != NULL))
   {
    const std::vector<mitk::ImageStatisticsCalculator::Statistics> &statistics =
      this->m_CalculationThread->GetStatisticsData();

    // Set time borders for for loop ;)
    unsigned int startT, endT;
    if(this->m_Controls->m_CheckBox4dCompleteTable->checkState()==Qt::CheckState::Unchecked)
    {
        startT = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()->
          GetPos();
        endT = startT+1;
    }
    else
    {
        startT = 0;
        endT = statistics.size();
    }
    QVector< QVector<QString> > statisticsTable;
    QStringList headline;

    // Create Headline
    headline << " "
             << "Mean"
             << "Median"
             << "StdDev"
             << "RMS"
             << "Max"
             << "Min"
             << "NumberOfVoxels"
             << "Skewness"
             << "Kurtosis"
             << "Uniformity"
             << "Entropy"
             << "MPP"
             << "UPP"
             << "V [mm³]";

    for(int i=0;i<headline.size();i++)
    {
        QVector<QString> row;
        row.append(headline.at(i));
        statisticsTable.append(row);
    }

    // Fill Table
    for(unsigned int t=startT;t<endT;t++)
    {
        // Copy statistics to clipboard ("%Ln" will use the default locale for
        // number formatting)
        QStringList value;
        value << QString::number(t)
              << QString::number(statistics[t].GetMean())
              << QString::number(statistics[t].GetMedian())
              << QString::number(statistics[t].GetSigma())
              << QString::number(statistics[t].GetRMS())
              << QString::number(statistics[t].GetMax())
              << QString::number(statistics[t].GetMin())
              << QString::number(statistics[t].GetN())
              << QString::number(statistics[t].GetSkewness())
              << QString::number(statistics[t].GetKurtosis())
              << QString::number(statistics[t].GetUniformity())
              << QString::number(statistics[t].GetEntropy())
              << QString::number(statistics[t].GetMPP())
              << QString::number(statistics[t].GetUPP())
              << QString::number(m_Controls->m_StatisticsTable->item(7, 0)->data(Qt::DisplayRole).toDouble());

         for(int z=0;z<value.size();z++)
         {
             statisticsTable[z].append(value.at(z));
         }
    }

    // Create output string
    QString clipboard;
    for(int i=0;i<statisticsTable.size();i++)
    {
        for(int t=0;t<statisticsTable.at(i).size();t++)
        {
            clipboard.append(statisticsTable.at(i).at(t));
            clipboard.append("\t");
        }
        clipboard.append("\n");
    }
    QApplication::clipboard()->setText(clipboard, QClipboard::Clipboard);
  }
  else
  {
    QApplication::clipboard()->clear();
  }
  QLocale::setDefault(tempLocal);
}
Esempio n. 30
0
void createHistograms(QVector<QImage> &histograms,
                      const QVector< shared_ptr<Granules> > &granules,
                      const shared_ptr<const Settings> &settings,
                      const QString &path,
                      double &minArea,
                      double &maxArea,
                      double &meanArea,
                      double &meanCompact) {

    histograms.clear();

    //

    if ( granules.size() == 0 ) { return; }

    //

    QVector<double> areas = granules[0]->areaValues();
    QVector<double> compacts = granules[0]->compactValues();

    for ( ptrdiff_t n=1; n<granules.size(); n++ ) {
        areas += granules[n]->areaValues();
        compacts += granules[n]->compactValues();
    }

    if ( areas.isEmpty()    ||
         compacts.isEmpty() ||
         (areas.size() != compacts.size()) ) { return; }

    //

    HistXSetup histAreasXSet;
    histAreasXSet.minval = areas[0];
    histAreasXSet.maxval = areas[0];

    HistXSetup histCompactsXSet;
    histCompactsXSet.minval = compacts[0];
    histCompactsXSet.maxval = compacts[0];

    minArea = areas[0];
    maxArea = areas[0];
    meanArea = areas[0];
    meanCompact = compacts[0];

    for ( ptrdiff_t i=1; i<areas.size(); i++ ) {

        if ( areas[i] < minArea ) { minArea = areas[i]; }
        if ( areas[i] > maxArea ) { maxArea = areas[i]; }

        meanArea += areas[i];
        meanCompact += compacts[i];

        //

        if ( areas[i] < histAreasXSet.minval ) {
            histAreasXSet.minval = areas[i];
        }

        if ( areas[i] > histAreasXSet.maxval ) {
            histAreasXSet.maxval = areas[i];
        }

        if ( compacts[i] < histCompactsXSet.minval ) {
            histCompactsXSet.minval = compacts[i];
        }

        if ( compacts[i] > histCompactsXSet.maxval ) {
            histCompactsXSet.maxval = compacts[i];
        }
    }

    meanArea /= areas.size();
    meanCompact /= compacts.size();

    histAreasXSet.step =
            (histAreasXSet.maxval - histAreasXSet.minval) / HISTDIMENSION;

    histCompactsXSet.step =
            (histCompactsXSet.maxval - histCompactsXSet.minval) / HISTDIMENSION;

    //

    QVector<double> histAreasVls;
    histAreasVls.resize(HISTDIMENSION);

    QVector<double> histCompactsVls;
    histCompactsVls.resize(HISTDIMENSION);

    double tmpmin1 = histAreasXSet.minval;
    double tmpmax1 = tmpmin1 + histAreasXSet.step;

    for ( ptrdiff_t n=0; n<areas.size(); n++ ) {

        for ( ptrdiff_t i=0; i<HISTDIMENSION; i++ ) {

            if ( i == (HISTDIMENSION-1) ) {

                if ( areas[n]>=tmpmin1 &&
                     areas[n]<(tmpmax1+histAreasXSet.step) ) {
                    histAreasVls[i]++;
                    break;
                }
            }
            else {

                if ( areas[n]>=tmpmin1 && areas[n]<tmpmax1 ) {
                    histAreasVls[i]++;
                    break;
                }
            }

            tmpmin1 += histAreasXSet.step;
            tmpmax1 += histAreasXSet.step;
        }

        tmpmin1 = histAreasXSet.minval;
        tmpmax1 = tmpmin1 + histAreasXSet.step;
    }

    for ( ptrdiff_t i=0; i<histAreasVls.size(); i++ ) {
        histAreasVls[i] /= areas.size();
    }

    //

    double tmpmin2 = histCompactsXSet.minval;
    double tmpmax2 = tmpmin2 + histCompactsXSet.step;

    for ( ptrdiff_t n=0; n<compacts.size(); n++ ) {

        for ( ptrdiff_t i=0; i<HISTDIMENSION; i++ ) {

            if ( i == (HISTDIMENSION-1) ) {

                if ( compacts[n]>=tmpmin2 &&
                     compacts[n]<(tmpmax2+histCompactsXSet.step) ) {
                    histCompactsVls[i]++;
                    break;
                }
            }
            else {
                if ( compacts[n]>=tmpmin2 && compacts[n]<tmpmax2 ) {
                    histCompactsVls[i]++;
                    break;
                }
            }

            tmpmin2 += histCompactsXSet.step;
            tmpmax2 += histCompactsXSet.step;
        }

        tmpmin2 = histCompactsXSet.minval;
        tmpmax2 = tmpmin2 + histCompactsXSet.step;
    }

    for ( ptrdiff_t i=0; i<histCompactsVls.size(); i++ ) {
        histCompactsVls[i] /= compacts.size();
    }

    //

    QVector<QwtIntervalSample> hist1data;

    double tmpmin1g = histAreasXSet.minval;
    double tmpmax1g = tmpmin1g + histAreasXSet.step;

    for ( ptrdiff_t i=0; i<HISTDIMENSION; i++ ) {

        hist1data.push_back(QwtIntervalSample(histAreasVls[i],
                                              tmpmin1g,
                                              tmpmax1g));

        tmpmin1g += histAreasXSet.step;
        tmpmax1g += histAreasXSet.step;
    }

    //

    QwtText xAxisTitle1(QObject::tr("Granule area"));
    xAxisTitle1.setFont(QFont("DejaVu Sans", 10));

    QwtText yAxisTitle1("n_i / N");
    yAxisTitle1.setFont(QFont("DejaVu Sans", 10));

    shared_ptr<QwtPlot> histogram1(new QwtPlot());
    histogram1->setPalette(QPalette(QColor(Qt::white)));
    histogram1->setFrameShape(QFrame::NoFrame);
    histogram1->setFrameShadow(QFrame::Plain);
    QFrame *frame_histogram1 = static_cast<QFrame *>(histogram1->canvas());
    frame_histogram1->setLineWidth(0);
    histogram1->setAxisTitle(QwtPlot::xBottom, xAxisTitle1);
    histogram1->setAxisTitle(QwtPlot::yLeft, yAxisTitle1);

    shared_ptr<QwtPlotHistogram> hist1(new QwtPlotHistogram());
    hist1->setStyle(QwtPlotHistogram::Columns);
    hist1->setRenderHint(QwtPlotItem::RenderAntialiased);

    hist1->setSamples(hist1data);
    hist1->attach(histogram1.get());

    histogram1->resize(600, 400);
    histogram1->replot();

    QPixmap pixmap1(histogram1->size());
    histogram1->render(&pixmap1);

    histograms.push_back(pixmap1.toImage());

    //

    QVector<QwtIntervalSample> hist2data;

    double tmpmin2g = histCompactsXSet.minval;
    double tmpmax2g = tmpmin2g + histCompactsXSet.step;

    for ( ptrdiff_t i=0; i<HISTDIMENSION; i++ ) {

        hist2data.push_back(QwtIntervalSample(histCompactsVls[i],
                                              tmpmin2g,
                                              tmpmax2g));

        tmpmin2g += histCompactsXSet.step;
        tmpmax2g += histCompactsXSet.step;
    }

    //

    QwtText xAxisTitle2(QObject::tr("Granule circularity"));
    xAxisTitle2.setFont(QFont("DejaVu Sans", 10));

    QwtText yAxisTitle2("n_i / N");
    yAxisTitle2.setFont(QFont("DejaVu Sans", 10));

    shared_ptr<QwtPlot> histogram2(new QwtPlot());
    histogram2->setPalette(QPalette(QColor(Qt::white)));
    histogram2->setFrameShape(QFrame::NoFrame);
    histogram2->setFrameShadow(QFrame::Plain);
    QFrame *frame_histogram2 = static_cast<QFrame *>(histogram2->canvas());
    frame_histogram2->setLineWidth(0);
    histogram2->setAxisTitle(QwtPlot::xBottom, xAxisTitle2);
    histogram2->setAxisTitle(QwtPlot::yLeft, yAxisTitle2);

    shared_ptr<QwtPlotHistogram> hist2(new QwtPlotHistogram());
    hist2->setStyle(QwtPlotHistogram::Columns);
    hist2->setRenderHint(QwtPlotItem::RenderAntialiased);

    hist2->setSamples(hist2data);
    hist2->attach(histogram2.get());

    histogram2->resize(600, 400);
    histogram2->replot();

    QPixmap pixmap2(histogram2->size());
    histogram2->render(&pixmap2);

    histograms.push_back(pixmap2.toImage());

    //

    if ( settings->val_createTmpImg() ) {
        saveHistograms(histograms, path);
    }
}