Example #1
0
void PuzzlePrinter::drawKillerSudokuCages (const SKGraph* graph,
                                           const QVector<int> & edges)
{
    // Killer Sudokus have cages AND groups: so the cages are drawn differently.
    // We keep the outer wall of the cage on our left and draw a dashed line
    // just inside that boundary.  This reduces ugly criss-crossing of lines.
    //
    // Directions and related arrays are all in clockwise order.
    enum  Direction {East, South, West, North, nDirections};
    const Direction rightTurn [nDirections] = {South, West, North, East};
    const Direction leftTurn [nDirections]  = {North, East, South, West};
    const int       wallOnLeft [nDirections] =
			    {1 << Above, 1 << Right, 1 << Below, 1 << Left};
    const int       wallAhead [nDirections] =
			    {1 << Right, 1 << Below, 1 << Left, 1 << Above};

    const int       deltaX  [nDirections] = {+1, 0, -1, 0};
    const int       deltaY  [nDirections] = {0, +1, 0, -1};

    int   cellInc [nDirections] = {graph->order(), +1, -graph->order(), -1};
    int   offset    = (m_sCell + 6) / 12;
    int   longSide  = m_sCell;
    int   shortSide = m_sCell - offset - offset;

    m_p->setPen (m_dashes);

    for (int n = 0; n < graph->cageCount(); n++) {
	int topLeft = graph->cageTopLeft(n);
	int cell    = topLeft;
	int edge    = edges.at (cell);
	int startX  = m_topX + m_sCell * graph->cellPosX (cell) + offset;
	int startY  = m_topY + m_sCell * graph->cellPosY (cell) + offset;
	int dx      = 0;
	int dy      = 0;
	QLine line (startX, startY, startX, startY);
	Direction direction = East;

	// Keep drawing until we get back to the starting cell and direction.
	do {
	    // If there is a wall on the left, follow it.
	    if (edge & wallOnLeft [direction]) {
		if (edge & wallAhead [direction]) {
		    // Go to wall (shortSide), draw line, turn right, new line.
		    dx = deltaX [direction] * shortSide;
		    dy = deltaY [direction] * shortSide;
		    line.setLine (line.x1(), line.y1(),
				  line.x2() + dx, line.y2() + dy);
		    m_p->drawLine (line);
		    direction = rightTurn [direction];
		    line.setLine (line.x2(), line.y2(), line.x2(), line.y2());
		}
		else {
		    // Extend to start of next cell (longSide).
		    dx = deltaX [direction] * longSide;
		    dy = deltaY [direction] * longSide;
		    line.setLine (line.x1(), line.y1(),
				  line.x2() + dx, line.y2() + dy);
		    cell = cell + cellInc [direction];
		    edge = edges.at (cell);
		}
	    }
	    // Else, if there is no wall on the left ...
	    else {
		// Draw line, turn left, new line, go to start of next cell.
		m_p->drawLine (line);
		direction = leftTurn [direction];
		dx = deltaX [direction] * (longSide - shortSide);
		dy = deltaY [direction] * (longSide - shortSide);
		line.setLine (line.x2(), line.y2(),
			      line.x2() + dx, line.y2() + dy);
		cell = cell + cellInc [direction];
		edge = edges.at (cell);

	    }
	} while (! ((cell == topLeft) && (direction == East)));
    }	// Draw next cage.
}
Example #2
0
bool TouchExtensionGlobal::postTouchEvent(QTouchEvent *event, Surface *surface)
{
    const QList<QTouchEvent::TouchPoint> points = event->touchPoints();
    const int pointCount = points.count();
    if (!pointCount)
        return false;

    QPointF surfacePos = surface->pos();
    wl_client *surfaceClient = surface->resource()->client();
    uint32_t time = m_compositor->currentTimeMsecs();
    const int rescount = m_resources.count();

    for (int res = 0; res < rescount; ++res) {
        wl_resource *target = m_resources.at(res);
        if (target->client != surfaceClient)
            continue;

        // We will use no touch_frame type of event, to reduce the number of
        // events flowing through the wire. Instead, the number of points sent is
        // included in the touch point events.
        int sentPointCount = 0;
        for (int i = 0; i < pointCount; ++i) {
            if (points.at(i).state() != Qt::TouchPointStationary)
                ++sentPointCount;
        }

        for (int i = 0; i < pointCount; ++i) {
            const QTouchEvent::TouchPoint &tp(points.at(i));
            // Stationary points are never sent. They are cached on client side.
            if (tp.state() == Qt::TouchPointStationary)
                continue;

            uint32_t id = tp.id();
            uint32_t state = (tp.state() & 0xFFFF) | (sentPointCount << 16);
            uint32_t flags = (tp.flags() & 0xFFFF) | (int(event->device()->capabilities()) << 16);

            QPointF p = tp.pos() - surfacePos; // surface-relative
            int x = toFixed(p.x());
            int y = toFixed(p.y());
            int nx = toFixed(tp.normalizedPos().x());
            int ny = toFixed(tp.normalizedPos().y());
            int w = toFixed(tp.rect().width());
            int h = toFixed(tp.rect().height());
            int vx = toFixed(tp.velocity().x());
            int vy = toFixed(tp.velocity().y());
            uint32_t pressure = uint32_t(tp.pressure() * 255);

            wl_array *rawData = 0;
            QVector<QPointF> rawPosList = tp.rawScreenPositions();
            int rawPosCount = rawPosList.count();
            if (rawPosCount) {
                rawPosCount = qMin(maxRawPos, rawPosCount);
                rawData = &m_rawdata_array;
                rawData->size = rawPosCount * sizeof(float) * 2;
                float *p = m_rawdata_ptr;
                for (int rpi = 0; rpi < rawPosCount; ++rpi) {
                    const QPointF &rawPos(rawPosList.at(rpi));
                    // This will stay in screen coordinates for performance
                    // reasons, clients using this data will presumably know
                    // what they are doing.
                    *p++ = float(rawPos.x());
                    *p++ = float(rawPos.y());
                }
            }

            qt_touch_extension_send_touch(target,
                                          time, id, state,
                                          x, y, nx, ny, w, h,
                                          pressure, vx, vy,
                                          flags, rawData);
        }

        return true;
    }

    return false;
}
Example #3
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;
}
void QmlProfilerEventsModelProxy::loadData(qint64 rangeStart, qint64 rangeEnd)
{
    clear();

    qint64 qmlTime = 0;
    qint64 lastEndTime = 0;
    QHash <int, QVector<qint64> > durations;

    const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1);

    const QVector<QmlProfilerDataModel::QmlEventData> &eventList
            = d->modelManager->qmlModel()->getEvents();
    const QVector<QmlProfilerDataModel::QmlEventTypeData> &typesList
            = d->modelManager->qmlModel()->getEventTypes();

    // used by binding loop detection
    QStack<const QmlProfilerDataModel::QmlEventData*> callStack;
    callStack.push(0); // artificial root

    for (int i = 0; i < eventList.size(); ++i) {
        const QmlProfilerDataModel::QmlEventData *event = &eventList[i];
        const QmlProfilerDataModel::QmlEventTypeData *type = &typesList[event->typeIndex];

        if (!d->acceptedTypes.contains(type->rangeType))
            continue;

        if (checkRanges) {
            if ((event->startTime + event->duration < rangeStart)
                    || (event->startTime > rangeEnd))
                continue;
        }

        // update stats
        QmlEventStats *stats = &d->data[event->typeIndex];

        stats->duration += event->duration;
        if (event->duration < stats->minTime)
            stats->minTime = event->duration;
        if (event->duration > stats->maxTime)
            stats->maxTime = event->duration;
        stats->calls++;

        // for median computing
        durations[event->typeIndex].append(event->duration);

        // qml time computation
        if (event->startTime > lastEndTime) { // assume parent event if starts before last end
            qmlTime += event->duration;
            lastEndTime = event->startTime + event->duration;
        }


        //
        // binding loop detection
        //
        const QmlProfilerDataModel::QmlEventData *potentialParent = callStack.top();
        while (potentialParent
               && !(potentialParent->startTime + potentialParent->duration > event->startTime)) {
            callStack.pop();
            potentialParent = callStack.top();
        }

        // check whether event is already in stack
        for (int ii = 1; ii < callStack.size(); ++ii) {
            if (callStack.at(ii)->typeIndex == event->typeIndex) {
                d->eventsInBindingLoop.insert(event->typeIndex);
                break;
            }
        }

        callStack.push(event);

        d->modelManager->modelProxyCountUpdated(d->modelId, i, eventList.count()*2);
    }

    // post-process: calc mean time, median time, percentoftime
    int i = d->data.size();
    int total = i * 2;

    for (QHash<int, QmlEventStats>::iterator it = d->data.begin(); it != d->data.end(); ++it) {
        QmlEventStats* stats = &it.value();
        if (stats->calls > 0)
            stats->timePerCall = stats->duration / (double)stats->calls;

        QVector<qint64> eventDurations = durations[it.key()];
        if (!eventDurations.isEmpty()) {
            qSort(eventDurations);
            stats->medianTime = eventDurations.at(eventDurations.count()/2);
        }

        stats->percentOfTime = stats->duration * 100.0 / qmlTime;
        d->modelManager->modelProxyCountUpdated(d->modelId, i++, total);
    }

    // set binding loop flag
    foreach (int typeIndex, d->eventsInBindingLoop)
        d->data[typeIndex].isBindingLoop = true;

    // insert root event
    QmlEventStats rootEvent;
    rootEvent.duration = rootEvent.minTime = rootEvent.maxTime = rootEvent.timePerCall
                       = rootEvent.medianTime = qmlTime + 1;
    rootEvent.calls = 1;
    rootEvent.percentOfTime = 100.0;

    d->data.insert(-1, rootEvent);

    d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1);
    emit dataAvailable();
}
Example #5
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;
}
Example #6
0
void GraphParamGlobal::setValues(QVector<double> val)
{
    for (int i = 0; i < qMin(this->nbPoints, val.size()); i++)
        dValues[i] = val.at(i);
}
void MainWindow::calcCentr()
{
    QVector<double> results;
    results = getResults(0,0);
    double max = 0.0;
    int tmp = 0;
//floy
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            FloydCentr.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }

    }
//dijk
    max = 0.0;
    tmp = 0;
    results = getResults(1,0);
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            DijkstraCentr.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }
    }
//rand
    max = 0.0;
    tmp = 0;
    results = getResults(2,0);
    qDebug() << "size" << results.size();
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            RandCentr.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }
    }

    //// TIME
    ///
    max = 0.0;
    tmp = 0;
    results = getResults(0,1);

    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            FloydCentrTime.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }

    }
    max = 0.0;
    tmp = 0;
    results = getResults(1,1);
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            DijkstraCentrTime.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }
    }

    max = 0.0;
    tmp = 0;
    results = getResults(2,1);
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            RandCentrTime.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }
    }
}
Example #8
0
/*! \void XCLProcessor::performSetLength(XCLSyntaxExpression* expr, QVector<XCLProcessParameter> param,XCLParsingItem* item)
 *  \brief Sets the length of the XCLSyntaxExpression \a expr to the value given by the parameters of the method.
 *  \param expr A pointer to the XCLSyntaxExpression, the processing method will be performed on.
 *  \param param A list of parameters for this method.
 *  \param item A pointer to the parent XCLParsingItem.
 *  \exception XCLException 


**/
void XCLProcessor::performSetLength(XCLSyntaxExpression* expr, QVector<XCLProcessParameter> param,FileParserState& item)
{
    _UINT32 count=0;
    QString count2; // referenced or calculated value as QString

    BOOL isBigEndian;
    QString interpretation;
try
{
    //Value and DataType is given   
    if(param.size()==2)
    {
        XCLProcessParameter p1=param.at(0); //the value
        XCLProcessParameter p2=param.at(1); //the data type

        QString type = p2.getValue(item.index);

        //value has to be calculated
        if (p1.getValueType() == XCLProcessParameter::MATHEX)
        {
        
            XCLCalculator calc;
            count2 = calc.parseExpression(p1.getValue(), item.index);
           
        //    count=XCLStringConverter::string2Number<_UINT32>(count2,"uint64",expr->getIsBigEndian()); //something funny returns here ???
            count=count2.toInt();
        }
        else
        {   
            XCLInputNormalizer normalizer;
            isBigEndian = (item.index.get(p1.getValueReference()))->at(0)->getIsBigEndian();
            interpretation = (item.index.get(p1.getValueReference()))->at(0)->getInterpretation();

            if (isBigEndian)
            {
       

		QByteArray ba = p1.getValueAsBA(&item.index);

		count = (normalizer.normalizeValue((UCHAR*)ba.data(),ba.size(),interpretation, isBigEndian)->toInt());
                //count = p1.getValue(item.index).toLong();
            }
            else
            {
         

		QByteArray ba = p1.getValueAsBA(&item.index);

		count = (normalizer.normalizeValue((UCHAR*)ba.data(),ba.size(),interpretation, isBigEndian)->toInt());

            }            
        }

        _UINT8 typeLength = getTypeLength(type);
     

        expr->setLength(count*typeLength);
     

    }
    else if (param.size()==1)
    {
        XCLProcessParameter p=param.at(0);
        
        //value has to be calculated
        if (p.getValueType() == XCLProcessParameter::MATHEX)
        {
            XCLCalculator calc;
            count = calc.parseExpression(p.getValue(), item.index);
       
            expr->setLength(count);
        }
        else
        {
            _UINT32 num1=p.getValue(item.index).toLong();
      
            expr->setLength(num1); 
    
        }

    }
    else
    {
throw XCLException("Possible candidates for setLength are: setLength( length ) or setLength( count , type )\n");

    }
}
catch(XCLException exception)
{
exception.message();
throw XCLException("XCLProcessor couln´t execute setLength()\n");
}
}
Example #9
0
void XCLProcessor::performSetName(XCLSyntaxExpression* expr, QVector<XCLProcessParameter> param,FileParserState& item)
{
  XCLProcessParameter p=param.at(0);

  expr->setName(p.getValue(item.index));
}
Example #10
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
	QStringList args = a.arguments();
	if (args.size() < 3) {
		QStringList usage;
		usage << args.at(0)
			  << "[train data]"
			  << "[test data]";
		qFatal("Too few arguments. Usage:\n%s\n", usage.join(" ").toStdString().c_str());
	}

	QFile trainFile(args.at(1));
	if (!trainFile.open(QIODevice::ReadOnly)) {
		qFatal("Failed to open train file %s.\n", trainFile.fileName().toStdString().c_str());
	}
	QFile testFile(args.at(2));
	if (!testFile.open(QIODevice::ReadOnly)) {
		qFatal("Failed to open test file %s.\n", testFile.fileName().toStdString().c_str());
	}

    QElapsedTimer loadTimer;
    loadTimer.start();
    FeatureImporter trainFeatures;
    FeatureImporter testFeatures;
#pragma omp sections
    {
#pragma omp section
        {
            trainFeatures.open(&trainFile);
        }
#pragma omp section
        {
            testFeatures.open(&testFile);
        }
    }
    int loadMsecs = loadTimer.elapsed();
    qDebug() << "loading took" << loadMsecs << "msecs";

	trainFile.close();
	testFile.close();

	QVector<QString> hash;
    QVector<qint8> trainClasses;
	for (int i = 0; i < trainFeatures.labels().size(); i++) {
        qint8 index = hash.indexOf(trainFeatures.labels().at(i));
		if (index == -1) {
			QString dbg("Appending label \"%1\" to hash at position %2. It has now value \"%3\"");
			hash.append(trainFeatures.labels().at(i));
			index = hash.size() - 1;
			//qDebug() << dbg.arg(trainFeatures.labels().at(i), QString::number(index), hash.at(index));
		}
		trainClasses.append(index);
	}

    ClassifierInterface *ci = new CpuClassifier();
    QVector<QVector<int> > classes;
    qDebug() << "starting classification";
    QList<int> k;

    bool ok = true;
    int i = 50;
    if (args.size() >= 4) {
        i = qMax(0, args.at(3).toInt(&ok));
    } else {
        ok = false;
    }
    if (!ok) {
        qDebug() << "no k given, assuming k = 50";
        i = 50;
    }
    qDebug() << "initial k:" << i;
    for (; i >= 1; i--) {
        k.append(i);
    }
    QElapsedTimer timer;
    timer.start();
	classes = ci->classify(trainFeatures.features(), testFeatures.features(),
						   trainClasses.constData(), NULL,
						   testFeatures.featuresPerItem(),
						   trainFeatures.itemCount(), testFeatures.itemCount(),
                           k);
    delete ci;
	int msecs = timer.elapsed();
	qDebug() << "calculations took" << msecs << "msecs";
    for (int w = 0; w < classes.size(); w++) {
        int correct = 0;
        QVector<QVector<qreal> > confusionMatrix;
        confusionMatrix.resize(hash.size());
        for (int i = 0; i < confusionMatrix.size(); i++) {
            confusionMatrix[i].resize(hash.size());
        }
        for (int i = 0; i < classes.at(w).size(); i++) {
            /*qDebug() << i;
            qDebug() << classes.at(i);
            qDebug() << hash.at(classes.at(i));
            qDebug() << testFeatures.labels().at(i);*/
            confusionMatrix[hash.indexOf(testFeatures.labels().at(i))][classes.at(w).at(i)]++;
            /*if (hash.at(classes.at(w).at(i)) == QString("5")) {
                qDebug() << "is 5, should be " << testFeatures.labels().at(i);
            }*/
            if (hash.at(classes.at(w).at(i)) == testFeatures.labels().at(i)) {
                correct++;
            }
        }
        QVector<QPair<QString, int> > sorter;
        for (int i = 0; i < hash.size(); i++) {
            sorter << qMakePair(hash.at(i), i);
        }
        qSort(sorter);
        QStringList l;
        for (int i = 0; i < hash.size(); i++) {
            l << sorter.at(i).first;
        }
        QVector<QVector<qreal> > tempConfusionMatrix;
        tempConfusionMatrix.resize(hash.size());
        for (int j = 0; j < confusionMatrix.size(); j++) {
            for (int i = 0; i < sorter.size(); i++) {
                tempConfusionMatrix[j] << confusionMatrix.at(j).at(sorter.at(i).second);
            }
        }
        confusionMatrix = tempConfusionMatrix;
        for (int j = 0; j < confusionMatrix.size(); j++) {
            tempConfusionMatrix[j] = confusionMatrix.at(sorter.at(j).second);
        }
        confusionMatrix = tempConfusionMatrix;
#ifdef PERCENTAGE_CONFUSION
        for (int i = 0; i < confusionMatrix.size(); i++) {
            qreal sum = 0;
            for (int j = 0; j < confusionMatrix.at(i).size(); j++) {
                sum += confusionMatrix.at(j).at(i);
            }
            for (int j = 0; j < confusionMatrix.at(i).size(); j++) {
                confusionMatrix[j][i] = confusionMatrix.at(j).at(i) / sum * 100.0;
            }
        }
#endif
        QTextStream stream(stdout);
        stream << "k: " << k.at(w) << endl;
        stream << "\t&\t" << l.join("\t&\t") << "\\\\" << endl;
        for (int i = 0; i < confusionMatrix.size(); i++) {
            QStringList list;
            list << sorter.at(i).first;
            for (int j = 0; j < confusionMatrix.size(); j++) {
                list << QString::number(confusionMatrix[i][j], 'g', 4);
            }
            const QString joined(list.join("\t&\t"));
            stream << joined << "\\\\" << endl;
        }
        stream << "correct: " << ((float)correct / (float)classes.at(w).size()) * 100 << "%" << endl;
    }
    msecs = timer.elapsed();
    qDebug() << "everything took" << msecs << "msecs";
	return 0;
}
Example #11
0
KisImageBuilder_Result CSVSaver::encode(const QUrl &uri,const QString &filename)
{
    int idx;
    int start, end;
    KisNodeSP node;
    QByteArray ba;
    KisKeyframeSP keyframe;
    QVector<CSVLayerRecord*> layers;

    KisImageAnimationInterface *animation = m_image->animationInterface();

    //open the csv file for writing
    QFile f(uri.toLocalFile());
    if (!f.open(QIODevice::WriteOnly)) {
        return KisImageBuilder_RESULT_NOT_LOCAL;
    }

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    //DataStream instead of TextStream for correct line endings
    QDataStream stream(&f);

    QString path = filename;

    if (path.right(4).toUpper() == ".CSV")
        path = path.left(path.size() - 4);

    path.append(".frames");

    //create directory

    QDir dir(path);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    //according to the QT docs, the slash is a universal directory separator
    path.append("/");

    m_image->lock();
    node = m_image->rootLayer()->firstChild();

    //TODO: correct handling of the layer tree.
    //for now, only top level paint layers are saved

    idx = 0;

    while (node) {
        if (node->inherits("KisPaintLayer")) {
            KisPaintLayer* paintLayer = dynamic_cast<KisPaintLayer*>(node.data());
            CSVLayerRecord* layerRecord = new CSVLayerRecord();
            layers.prepend(layerRecord); //reverse order!

            layerRecord->name = paintLayer->name();
            layerRecord->name.replace(QRegExp("[\"\\r\\n]"), "_");

            if (layerRecord->name.isEmpty())
                layerRecord->name= QString("Unnamed-%1").arg(idx);

            layerRecord->visible = (paintLayer->visible()) ? 1 : 0;
            layerRecord->density = (float)(paintLayer->opacity()) / OPACITY_OPAQUE_U8;
            layerRecord->blending = convertToBlending(paintLayer->compositeOpId());
            layerRecord->layer = paintLayer;
            layerRecord->channel = paintLayer->projection()->keyframeChannel();
            layerRecord->last = "";
            layerRecord->frame = 0;
            idx++;
        }
        node = node->nextSibling();
    }

    KisTimeRange range = animation->fullClipRange();

    start = (range.isValid()) ? range.start() : 0;

    if (!range.isInfinite()) {
        end = range.end();

        if (end < start) end = start;
    } else {
        //undefined length, searching for the last keyframe
        end = start;

        for (idx = 0; idx < layers.size(); idx++) {
            keyframe = layers.at(idx)->channel->lastKeyframe();

            if ( (!keyframe.isNull()) && (keyframe->time() > end) )
                end = keyframe->time();
        }
    }

    //create temporary doc for exporting
    QScopedPointer<KisDocument> exportDoc(KisPart::instance()->createDocument());
    createTempImage(exportDoc.data());

    KisImageBuilder_Result retval= KisImageBuilder_RESULT_OK;

    if (!m_batchMode) {
        emit m_doc->statusBarMessage(i18n("Saving CSV file..."));
        emit m_doc->sigProgress(0);
        connect(m_doc, SIGNAL(sigProgressCanceled()), this, SLOT(cancel()));
    }
    int frame = start;
    int step = 0;

    do {
        qApp->processEvents();

        if (m_stop) {
            retval = KisImageBuilder_RESULT_CANCEL;
            break;
        }

        switch(step) {

        case 0 :    //first row
            if (f.write("UTF-8, TVPaint, \"CSV 1.0\"\r\n") < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
            }
            break;

        case 1 :    //scene header names
            if (f.write("Project Name, Width, Height, Frame Count, Layer Count, Frame Rate, Pixel Aspect Ratio, Field Mode\r\n") < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
            }
            break;

        case 2 :    //scene header values
            ba = QString("\"%1\", ").arg(m_image->objectName()).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            ba = QString("%1, %2, ").arg(m_image->width()).arg(m_image->height()).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }

            ba = QString("%1, %2, ").arg(end - start + 1).arg(layers.size()).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            //the framerate is an integer here
            ba = QString("%1, ").arg((double)(animation->framerate()),0,'f',6).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            ba = QString("%1, Progressive\r\n").arg((double)(m_image->xRes() / m_image->yRes()),0,'f',6).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            break;

        case 3 :    //layer header values
            if (f.write("#Layers") < 0) {          //Layers
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }

            for (idx = 0; idx < layers.size(); idx++) {
                ba = QString(", \"%1\"").arg(layers.at(idx)->name).toUtf8();
                if (f.write(ba.data()) < 0)
                    break;
            }
            break;

        case 4 :
            if (f.write("\r\n#Density") < 0) {     //Density
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            for (idx = 0; idx < layers.size(); idx++) {
                ba = QString(", %1").arg((double)(layers.at(idx)->density), 0, 'f', 6).toUtf8();
                if (f.write(ba.data()) < 0)
                    break;
            }
            break;

        case 5 :
            if (f.write("\r\n#Blending") < 0) {     //Blending
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            for (idx = 0; idx < layers.size(); idx++) {
                ba = QString(", \"%1\"").arg(layers.at(idx)->blending).toUtf8();
                if (f.write(ba.data()) < 0)
                    break;
            }
            break;

        case 6 :
            if (f.write("\r\n#Visible") < 0) {     //Visible
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }
            for (idx = 0; idx < layers.size(); idx++) {
                ba = QString(", %1").arg(layers.at(idx)->visible).toUtf8();
                if (f.write(ba.data()) < 0)
                    break;
            }
            if (idx < layers.size()) {
                retval = KisImageBuilder_RESULT_FAILURE;
            }
            break;

        default :    //frames

            if (frame > end) {
                if (f.write("\r\n") < 0)
                    retval = KisImageBuilder_RESULT_FAILURE;

                step = 8;
                break;
            }

            ba = QString("\r\n#%1").arg(frame, 5, 10, QChar('0')).toUtf8();
            if (f.write(ba.data()) < 0) {
                retval = KisImageBuilder_RESULT_FAILURE;
                break;
            }

            for (idx = 0; idx < layers.size(); idx++) {
                CSVLayerRecord *layer = layers.at(idx);
                keyframe = layer->channel->keyframeAt(frame);

                if (!keyframe.isNull()) {
                    if (!m_batchMode) {
                        emit m_doc->sigProgress(((frame - start) * layers.size() + idx) * 100 /
                                                ((end - start) * layers.size()));
                    }
                    retval = getLayer(layer, exportDoc.data(), keyframe, path, frame, idx);

                    if (retval != KisImageBuilder_RESULT_OK)
                        break;
                }
                ba = QString(", \"%1\"").arg(layer->last).toUtf8();

                if (f.write(ba.data()) < 0)
                    break;
            }
            if (idx < layers.size())
                retval = KisImageBuilder_RESULT_FAILURE;

            frame++;
            step = 6; //keep step here
            break;
        }
        step++;
    } while((retval == KisImageBuilder_RESULT_OK) && (step < 8));

    m_image->unlock();

    qDeleteAll(layers);
    f.close();

    if (!m_batchMode) {
        disconnect(m_doc, SIGNAL(sigProgressCanceled()), this, SLOT(cancel()));
        emit m_doc->sigProgress(100);
        emit m_doc->clearStatusBarMessage();
    }
    QApplication::restoreOverrideCursor();
    return retval;
}
Example #12
0
void trakkermodel::drawHyper(float hyper_a, float hyper_c, int rotation ){


    double x1t,x2t,y1t,y2t, x1tm, x2tm, y1tm, y2tm ;

    int hyp1x =   0; // variables to translate proper hyperbolas
    int hyp1y = -29;
    float i;

    QVector<float> x;
    QVector<float> y1;
    QVector<float> y2;
    QVector<float> xShifted;

    sigDrawLine(10,-50,-29,50,-29,'k');  // triangle
    sigDrawLine(10,-50,-29,0 , 56,'k');
    sigDrawLine(10,  0, 56,50,-29,'k');

    sigDrawLine(10,  -2, 0,2,0,'k');
    sigDrawLine(10,  0, -2,0,2,'k');



    //calculation
    if ( hyper_a  > 0 ){
        for (i = 0 ; i < 200; i++){  // i and x are prescaled in meter so 'i' is iterated by 10cm
            x.append(i/10 + hyper_a);
            y1.append(   sqrt(   abs( (hyper_c*hyper_c - hyper_a*hyper_a )*(   (x.at(i)*x.at(i))/(hyper_a*hyper_a) -1 ) )    ));
            y2.append( - sqrt(   abs( (hyper_c*hyper_c - hyper_a*hyper_a )*(   (x.at(i)*x.at(i))/(hyper_a*hyper_a) -1 ) )    ));
        }
    }else{
        if (hyper_a  < 0 ){
            for (i = 0 ; i < 200; i = i++){
                x.append(-i/10 + hyper_a);
                y1.append(   sqrt(   abs( (hyper_c*hyper_c - hyper_a*hyper_a )*(  (x.at(i)*x.at(i))/(hyper_a*hyper_a) -1 ) )    ));
                y2.append( - sqrt(   abs( (hyper_c*hyper_c - hyper_a*hyper_a )*(  (x.at(i)*x.at(i))/(hyper_a*hyper_a) -1 ) )    ));
            }
        }else{  // hyper_a = 0;
            x.append(0);
            x.append(0);

            y1.append(0);
            y1.append(-500);
            y2.append(0);
            y2.append(500);


        }

    }

    for (i = 0 ; i < x.size() ; i++){
        xShifted.append( x.at(i) + 10*hyper_a );
    }



    //drawing
    switch (rotation){
    case 0:

            for (i = 0 ; i < xShifted.size() -1 ; i++){
                sigDrawLine(10 , -10*xShifted.at(i) +hyp1x ,10* y1.at(i) +hyp1y,- 10*xShifted.at(i+1)+hyp1x ,10*  y1.at(i+1)+hyp1y , 'b');
                sigDrawLine(10 , -10*xShifted.at(i) +hyp1x ,10* y2.at(i) +hyp1y,- 10*xShifted.at(i+1)+hyp1x ,10*  y2.at(i+1)+hyp1y , 'b');
            }
            break;

    case 120:
            x2t  = (10*xShifted.at(0)+hyp1x) * (-0.5) - (10*y1.at(0)+hyp1y)* 0.866 ;
            x2tm = x2t;
            y2t  = (10*xShifted.at(0)+hyp1x) * 0.866  + (10*y1.at(0)+hyp1y)*(-0.5) ;
            y2tm = y2t;

            for (i = 0 ; i < xShifted.size() -1 ; i++){
                x1t  = x2t;
                x1tm = x2tm;

                x2t  = (10*xShifted.at(i+1)+hyp1x) * (-0.5) - (10*y1.at(i+1)+hyp1y)* 0.866 ;
                x2tm = (10*xShifted.at(i+1)+hyp1x) * (-0.5) - (10*y2.at(i+1)+hyp1y)* 0.866 ;

                y1t  = y2t;
                y1tm = y2tm;

                y2t  = (10*xShifted.at(i+1)+hyp1x) * 0.866  + (10*y1.at(i+1)+hyp1y)*(-0.5) ;
                y2tm = (10*xShifted.at(i+1)+hyp1x) * 0.866  + (10*y2.at(i+1)+hyp1y)*(-0.5) ;
                sigDrawLine(10, x1t  ,y1t  ,x2t  ,y2t  , 'r');
                sigDrawLine(10, x1tm ,y1tm ,x2tm ,y2tm , 'r');
            }
            break;

    case 240:
            x2t  = (-10*xShifted.at(0)+hyp1x) * (-0.5) + (10*y1.at(0)+hyp1y)*0.866 ;
            x2tm = x2t;
            y2t  = (-10*xShifted.at(0)+hyp1x) *(-0.866)  + (10*y1.at(0)+hyp1y)*(-0.5) ;
            y2tm = y2t;

            for (i = 0 ; i < xShifted.size() -1 ; i++){
                x1t  = x2t;
                x1tm = x2tm;

                x2t  = (-10*xShifted.at(i+1)+hyp1x) * (-0.5) + (10*y1.at(i+1)+hyp1y)* 0.866 ;
                x2tm = (-10*xShifted.at(i+1)+hyp1x) * (-0.5) + (10*y2.at(i+1)+hyp1y)* 0.866 ;

                y1t  = y2t;
                y1tm = y2tm;

                y2t  = (-10*xShifted.at(i+1)+hyp1x)*(-0.866)  + (10*y1.at(i+1)+hyp1y)*(-0.5) ;
                y2tm = (-10*xShifted.at(i+1)+hyp1x)*(-0.866)  + (10*y2.at(i+1)+hyp1y)*(-0.5) ;
                sigDrawLine(10, x1t  ,y1t  ,x2t  ,y2t  , 'g');
                sigDrawLine(10, x1tm ,y1tm ,x2tm ,y2tm , 'g');
            }
            break;

    default:
            for (i = 0 ; i < x.size() ; i++){
                sigDrawLine(10 , x.at(i) +hyp1x , y1.at(i) +hyp1y, x.at(i)+hyp1x,  y1.at(i)+hyp1y , 'm');
                sigDrawLine(10 , x.at(i) +hyp1x , y2.at(i) +hyp1y, x.at(i)+hyp1x,  y2.at(i)+hyp1y , 'm');
            }
            break;
    }

}
void tst_ExceptionSafety::exceptionVector() {

    {
        QVector<FlexibleThrowerSmall> vector;
        QVector<FlexibleThrowerSmall> vector2;
        QVector<FlexibleThrowerSmall> vector3;

        for (int i = 0; i<10; i++)
            vector.append( FlexibleThrowerSmall(i) );

        try {
            throwType = ThrowAtCopy;
            vector.append( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector.prepend( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector.insert( 8, FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.at(8).value(), 8 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector3 = vector;
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(0).value(), 0 );
        QCOMPARE( vector3.at(7).value(), 7 );
        QCOMPARE( vector3.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector3.append( FlexibleThrowerSmall(11) );
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(0).value(), 0 );
        QCOMPARE( vector3.at(7).value(), 7 );

        try {
            vector2.clear();
            vector2.append( FlexibleThrowerSmall(11));
            throwType = ThrowAtCopy;
            vector3 = vector+vector2;
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        // check that copy on write works atomar
        vector2.clear();
        vector2.append( FlexibleThrowerSmall(11));
        vector3 = vector+vector2;
        try {
            throwType = ThrowAtCreate;
            vector3[7]=FlexibleThrowerSmall(12);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(7).value(), 7 );
        QCOMPARE( vector3.size(), 11 );

        try {
            throwType = ThrowAtCreate;
            vector.resize(15);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCreate;
            vector.resize(15);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowLater;
            vector.fill(FlexibleThrowerSmall(1), 15);
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.size(), 10 );


    }
    QCOMPARE(objCounter, 0 ); // check that every object has been freed
}
Example #14
0
void PainterThread::drawAttrib(QPainter *p, Attributes *attrib)
{
    if (attrib->getType() == TObsAgent)
        return;

    //---- Desenha o atributo
    p->begin(attrib->getImage());

    p->setPen(Qt::NoPen); //defaultPen);

	//@RAIAN: Desenhando a vizinhanca
	if (attrib->getType() == TObsNeighborhood)
	{
		QColor color(Qt::white);
                QVector<QMap<QString, QList<double> > > *neighborhoods = attrib->getNeighValues();
		QVector<ObsLegend> *vecLegend = attrib->getLegend();

		QPen pen = p->pen();
		pen.setStyle(Qt::SolidLine);
		pen.setWidth(attrib->getWidth());

        // int random = qrand() % 256;
		double xCell = -1.0, yCell = -1.0;

		for (int pos = 0; pos < neighborhoods->size(); pos++)
		{
            QMap<QString, QList<double> > neigh = neighborhoods->at(pos);

			xCell = attrib->getXsValue()->at(pos);
			yCell = attrib->getYsValue()->at(pos);

			if ((xCell >= 0) && (yCell >=0))
			{
                QMap<QString, QList<double> >::Iterator itNeigh = neigh.begin();

				while (itNeigh != neigh.end())
				{
					QString neighID = itNeigh.key();
					QList<double> neighbor = itNeigh.value();

					double xNeigh = neighbor.at(0);
					double yNeigh = neighbor.at(1);
					double weight = neighbor.at(2);

					if (vecLegend->isEmpty())
					{
						weight = weight - attrib->getMinValue();
						double c = weight * attrib->getVal2Color();
						if (c >= 0 && c <= 255)
						{
							color.setRgb(c, c, c);
						}
						else
						{
							color.setRgb(255, 255, 255);
						}

						pen.setColor(color);
					}
					else
					{
						for (int j = 0; j < vecLegend->size(); j++)
						{
							ObsLegend leg = vecLegend->at(j);
							if (attrib->getGroupMode() == 3)
							{
								if (weight == leg.getTo().toDouble())
								{
									pen.setColor(leg.getColor());
									break;
								}
							}
							else
							{
								if ((leg.getFrom().toDouble() <= weight) && (weight < leg.getTo().toDouble()))
								{
									pen.setColor(leg.getColor());
									break;
								}
							}
						}
					}
					p->setPen(pen);

					if ((xNeigh >= 0) && (yNeigh >= 0))
					{
						drawNeighborhood(p, xCell, yCell, xNeigh, yNeigh);
					}

					itNeigh++;
				}
			}
		}
	}
	//@RAIAN: FIM
	else
	{
		if (attrib->getDataType() == TObsNumber)
		{
			QColor color(Qt::white);
			QVector<double> *values = attrib->getNumericValues();
			QVector<ObsLegend> *vecLegend = attrib->getLegend();

			double x = -1.0, y = -1.0, v = 0.0;

			int vSize = values->size();
			int xSize = attrib->getXsValue()->size();
			int ySize = attrib->getYsValue()->size();

			for (int pos = 0; (pos < vSize && pos < xSize && pos < ySize); pos++)
			{
				v = values->at(pos);

				// Corrige o bug gerando quando um agente morre
				if (attrib->getXsValue()->isEmpty() || attrib->getXsValue()->size() == pos)
					break;

				x = attrib->getXsValue()->at(pos);
				y = attrib->getYsValue()->at(pos);

				if (vecLegend->isEmpty())
				{
					v = v - attrib->getMinValue();

					double c = v * attrib->getVal2Color();
					if ((c >= 0) && (c <= 255))
					{
						color.setRgb(c, c, c);
					}
					else
					{
						color.setRgb(255, 255, 255);
					}
					p->setBrush(color);
				}
				else
				{
					for (int j = 0; j < vecLegend->size(); j++)
					{
						p->setBrush(Qt::white);

						const ObsLegend &leg = vecLegend->at(j);
						if (attrib->getGroupMode() == TObsUniqueValue) // valor ?nico 3
						{
							if (v == leg.getToNumber())
							{
								p->setBrush(leg.getColor());
								break;
							}
						}
						else
						{
							if ((leg.getFromNumber() <= v) && (v < leg.getToNumber()))
							{
								p->setBrush(leg.getColor());
								break;
							}
						}
					}
				}
				if ((x >= 0) && (y >= 0))
					draw(p, attrib->getType(), x, y);
			}
		}
		else if (attrib->getDataType() == TObsText)
		{
			QVector<QString> *values = attrib->getTextValues();
			QVector<ObsLegend> *vecLegend = attrib->getLegend();

            int random = qrand() % 256;
			double x = -1.0, y = -1.0;

			int vSize = values->size();
			int xSize = attrib->getXsValue()->size();
			int ySize = attrib->getYsValue()->size();

			for (int pos = 0; (pos < vSize && pos < xSize && pos < ySize); pos++)
			{
				const QString & v = values->at(pos);

				// Corrige o bug gerando quando um agente morre
				if (attrib->getXsValue()->isEmpty() || attrib->getXsValue()->size() == pos)
					break;

				x = attrib->getXsValue()->at(pos);
				y = attrib->getYsValue()->at(pos);

				if (vecLegend->isEmpty())
				{
					p->setBrush(QColor(random, random, random));
				}
				else
				{
					p->setBrush(Qt::white);
					for (int j = 0; j < vecLegend->size(); j++)
					{
						const ObsLegend &leg = vecLegend->at(j);
						if (v == leg.getFrom())
						{
							p->setBrush(leg.getColor());
							break;
						}
					}
				}

				if ((x >= 0) && (y >= 0))
					draw(p, attrib->getType(), x, y);
			}
		}
	}
    p->end();
}
Example #15
0
bool QSQLiteResult::exec()
{
    const QVector<QVariant> values = boundValues();

    d->skippedStatus = false;
    d->skipRow = false;
    d->rInf.clear();
    clearValues();
    setLastError(QSqlError());

    int res = sqlite3_reset(d->stmt);
    if (res != SQLITE_OK) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                     "Unable to reset statement"), QSqlError::StatementError, res));
        d->finalize();
        return false;
    }
    int paramCount = sqlite3_bind_parameter_count(d->stmt);
    if (paramCount == values.count()) {
        for (int i = 0; i < paramCount; ++i) {
            res = SQLITE_OK;
            const QVariant value = values.at(i);

            if (value.isNull()) {
                res = sqlite3_bind_null(d->stmt, i + 1);
            } else {
                switch (value.type()) {
                case QVariant::ByteArray: {
                    const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
                    res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(),
                                            ba->size(), SQLITE_STATIC);
                    break; }
                case QVariant::Int:
                    res = sqlite3_bind_int(d->stmt, i + 1, value.toInt());
                    break;
                case QVariant::Double:
                    res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble());
                    break;
                case QVariant::UInt:
                case QVariant::LongLong:
                    res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong());
                    break;
                case QVariant::String: {
                    // lifetime of string == lifetime of its qvariant
                    const QString *str = static_cast<const QString*>(value.constData());
                    res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(),
                                              (str->size()) * sizeof(QChar), SQLITE_STATIC);
                    break; }
                default: {
                    QString str = value.toString();
                    // SQLITE_TRANSIENT makes sure that sqlite buffers the data
                    res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
                                              (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
                    break; }
                }
            }
            if (res != SQLITE_OK) {
                setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                             "Unable to bind parameters"), QSqlError::StatementError, res));
                d->finalize();
                return false;
            }
        }
    } else {
        setLastError(QSqlError(QCoreApplication::translate("QSQLiteResult",
                        "Parameter count mismatch"), QString(), QSqlError::StatementError));
        return false;
    }
    d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    setSelect(!d->rInf.isEmpty());
    setActive(true);
    return true;
}
void PasswordsContentsWidget::removePasswords()
{
	const QModelIndexList indexes(m_ui->passwordsViewWidget->selectionModel()->selectedIndexes());

	if (indexes.isEmpty())
	{
		return;
	}

	QVector<PasswordsManager::PasswordInformation> passwords;
	passwords.reserve(indexes.count());

	for (int i = 0; i < indexes.count(); ++i)
	{
		if (!indexes.at(i).isValid() || indexes.at(i).column() > 0)
		{
			continue;
		}

		if (indexes.at(i).parent() == m_model->invisibleRootItem()->index())
		{
			const QModelIndex hostIndex(indexes.at(i));

			if (!hostIndex.isValid())
			{
				continue;
			}

			for (int j = 0; j < m_model->rowCount(hostIndex); ++j)
			{
				passwords.append(getPassword(m_model->index(j, 0, hostIndex)));
			}
		}
		else
		{
			const QModelIndex setIndex((indexes.at(i).parent().parent() == m_model->invisibleRootItem()->index()) ? indexes.at(i) : indexes.at(i).parent());

			if (setIndex.isValid())
			{
				passwords.append(getPassword(setIndex));
			}
		}
	}

	if (passwords.isEmpty())
	{
		return;
	}

	QMessageBox messageBox;
	messageBox.setWindowTitle(tr("Question"));
	messageBox.setText(tr("You are about to delete %n password(s).", "", passwords.count()));
	messageBox.setInformativeText(tr("Do you want to continue?"));
	messageBox.setIcon(QMessageBox::Question);
	messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
	messageBox.setDefaultButton(QMessageBox::Yes);

	if (messageBox.exec() == QMessageBox::Yes)
	{
		for (int i = 0; i < passwords.count(); ++i)
		{
			PasswordsManager::removePassword(passwords.at(i));
		}
	}
}
Example #17
0
// Main window constructor
BairesWindow::BairesWindow()
{
    ui.setupUi(this);

    if (!QSqlDatabase::drivers().contains("QSQLITE"))
        QMessageBox::critical(this, "Unable to load database", "This demo needs the SQLITE driver");

    // Initialize the database
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");

    if (!db.open())
        return;

    QStringList tables = db.tables();
    if (tables.contains("profiles", Qt::CaseInsensitive))
        return;

    QSqlQuery q;
	// Create profiles table
    if (!q.exec(QLatin1String("create table profiles(id integer primary key, "
                              "linkedin_profile text, "
                              "name text, "
                              "last_name text, "
                              "title text, "
                              "geographic_area text, "
                              "recommendations_count integer, "
                              "connections_count integer, "
                              "current_role text, "
                              "industry text, "
                              "country text "
                              ")"))) {
        return;
    }

	// Prepare insert query
    if (!q.prepare(QLatin1String("insert into profiles("
                                 "linkedin_profile, "
                                 "name, "
                                 "last_name, "
                                 "title, "
                                 "geographic_area, "
                                 "recommendations_count, "
                                 "connections_count, "
                                 "current_role, "
                                 "industry, "
                                 "country"
                                 ")"
                                 "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))) {
        return;
    }   

	// Begin to read data from text file
    QFile inputFile(":/PeopleToRate.txt");
    if (inputFile.open(QIODevice::ReadOnly))
    {
        QTextStream in(&inputFile);
        
        while (!in.atEnd())
        {
            QString line = in.readLine();
            QVector<QString> sequence;
            parseLineFields(line, sequence);
        
            // 0 PublicProfileURL
            // 1 Name
            // 2 LastName
            // 3 Title            
            // 4 GeographicArea            
            // 5 NumberOfRecommendations
            // 6 NumberOfConnections
            // 7 CurrentRole and Industry            
            // 8 Industry            
            // 9 Country            

			// Add register to database
            addProfile(q,
                        sequence.at(0),
                        sequence.at(1),
                        sequence.at(2),
                        sequence.at(3),
                        sequence.at(4),
                        sequence.at(5).toInt(),
                        sequence.at(6).toInt(),
                        sequence.at(7),
                        sequence.at(8),
                        sequence.at(9));
        }        
    }    

	// Query main industries
    QSqlQuery query(db);	
    query.exec("select distinct industry, count(industry) from profiles group by industry order by count(industry) desc");

	// Populate combobox
    while (query.next()) {
        QString name = query.value(0).toString();
        industryList << name;
    }

    ui.filterByCombo->addItems(industryList);

	// Ugly part, just hidding test components used for development of queries
    ui.executeQueryButton->setVisible(false);
    ui.groupBox_2->setVisible(false);
    ui.customersTable->setVisible(false);
}
Example #18
0
void renderCode128(OROPage * page, const QRectF & r, const QString & _str, ORBarcodeData * bc)
{
  QVector<int> str;
  int i = 0;

  // create the list.. if the list is empty then just set a start code and move on
  if(_str.isEmpty())
    str.push_back(104);
  else
  {
    int rank_a = 0;
    int rank_b = 0;
    int rank_c = 0;

    QChar c;
    for(i = 0; i < _str.length(); i++)
    {
      c = _str.at(i);
      rank_a += (code128Index(c, SETA) != -1 ? 1 : 0);
      rank_b += (code128Index(c, SETB) != -1 ? 1 : 0);
      rank_c += (c >= '0' && c <= '9' ? 1 : 0);
    }
    if(rank_c == _str.length() && ((rank_c % 2) == 0 || rank_c > 4))
    {
      // every value in the is a digit so we are going to go with mode C
      // and we have an even number or we have more than 4 values
      i = 0;
      if((rank_c % 2) == 1)
      {
        str.push_back(104); // START B
        c = _str.at(0);
        str.push_back(code128Index(c, SETB));
        str.push_back(99); // MODE C
        i = 1;
      }
      else
        str.push_back(105); // START C

      for(i = i; i < _str.length(); i+=2)
      {
        char a, b;
        c = _str.at(i);
        a = c.toLatin1();
        a -= 48;
        c = _str.at(i+1);
        b = c.toLatin1();
        b -= 48;
        str.push_back(int((a * 10) + b));
      }
    }
    else
    {
      // start in the mode that had the higher number of hits and then
      // just shift into the opposite mode as needed
      int set = ( rank_a > rank_b ? SETA : SETB );
      str.push_back(( rank_a > rank_b ? 103 : 104 ));
      int v = -1;
      for(i = 0; i < _str.length(); i++)
      {
        c = _str.at(i);
        v = code128Index(c, set);
        if(v == -1)
        {
          v = code128Index(c, (set == SETA ? SETB : SETA));
          if(v != -1)
          {
            str.push_back(98); // SHIFT
            str.push_back(v);
          }
        }
        else
          str.push_back(v);
      }
    }
  }

  // calculate and append the checksum value to the list
  int checksum = str.at(0);
  for(i = 1; i < str.size(); i++)
    checksum += (str.at(i) * i);
  checksum = checksum % 103;
  str.push_back(checksum);

  // lets determine some core attributes about this barcode
  qreal bar_width = bc->narrowBarWidth; 

  // this is are mandatory minimum quiet zone
  qreal quiet_zone = bar_width * 10;
  if(quiet_zone < 0.1)
    quiet_zone = 0.1;

  // what kind of area do we have to work with
  qreal draw_width = r.width();
  qreal draw_height = r.height();

  // how long is the value we need to encode?
  int val_length = str.size() - 2; // we include start and checksum in are list so
                                   // subtract them out for our calculations

  // L = (11C + 35)X 
  // L length of barcode (excluding quite zone) in units same as X and I
  // C the number of characters in the value excluding the start/stop and checksum characters
  // X the width of a bar (pixels in our case)
  qreal L;

  qreal C = val_length;
  qreal X = bar_width;

  L = (((11.0 * C) + 35.0) * X);

  // now we have the actual width the barcode will be so can determine the actual
  // size of the quiet zone (we assume we center the barcode in the given area
  // what should we do if the area is too small????
  // At the moment the way the code is written is we will always start at the minimum
  // required quiet zone if we don't have enough space.... I guess we'll just have over-run
  // to the right
  //
  // calculate the starting position based on the alignment option
  // for left align we don't need to do anything as the values are already setup for it
  if(bc->align == 1) // center
  {
    qreal nqz = (draw_width - L) / 2.0;
    if(nqz > quiet_zone)
      quiet_zone = nqz;
  }
  else if(bc->align > 1) // right
    quiet_zone = draw_width - (L + quiet_zone);
  // else if(align < 1) {} // left : do nothing

  qreal pos = r.left() + quiet_zone;
  qreal top = r.top();

  QPen pen(Qt::NoPen);
  QBrush brush(QColor("black"));

  bool space = false;
  int idx = 0, b = 0;
  qreal w = 0.0;
  for(i = 0; i < str.size(); i++)
  {
    // loop through each value and render the barcode
    idx = str.at(i);
    if(idx < 0 || idx > 105)
    {
      qDebug("Encountered a non-compliant element while rendering a 3of9 barcode -- skipping");
      continue;
    }
    space = false;
    for(b = 0; b < 6; b++, space = !space)
    {
      w = _128codes[idx].values[b] * bar_width;
      if(!space)
      {
        ORORect * rect = new ORORect(bc);
        rect->setPen(pen);
        rect->setBrush(brush);
        rect->setRect(QRectF(pos,top, w,draw_height));
		rect->setRotationAxis(r.topLeft());
        page->addPrimitive(rect);
      }
      pos += w;
    }
  }

  // we have to do the stop character seperatly like this because it has
  // 7 elements in it's bar sequence rather than 6 like the others
  int STOP_CHARACTER[]={ 2, 3, 3, 1, 1, 1, 2 };
  space = false;
  for(b = 0; b < 7; b++, space = !space)
  {
    w = STOP_CHARACTER[b] * bar_width;
    if(!space)
    {
      ORORect * rect = new ORORect(bc);
      rect->setPen(pen);
      rect->setBrush(brush);
      rect->setRect(QRectF(pos,top, w,draw_height));
	  rect->setRotationAxis(r.topLeft());
      page->addPrimitive(rect);
    }
    pos += w;
  }

  return;
} 
Example #19
0
//! [2]
void DBScreen::solidFill(const QColor &color, const QRegion &region)
{
    QVector<QRect> rects = region.rects();
    for (int i = 0; i  < rects.size(); i++)
        painter->fillRect(rects.at(i), color);
}
Example #20
0
QPainterPath TextEditorOverlay::createSelectionPath(const QTextCursor &begin, const QTextCursor &end,
                                                    const QRect &clip)
{
    if (begin.isNull() || end.isNull() || begin.position() > end.position())
        return QPainterPath();

    QPointF offset = m_editor->contentOffset();
    QRect viewportRect = rect();
    QTextDocument *document = m_editor->document();

    if (m_editor->blockBoundingGeometry(begin.block()).translated(offset).top() > clip.bottom() + 10
        || m_editor->blockBoundingGeometry(end.block()).translated(offset).bottom() < clip.top() - 10
        )
        return QPainterPath(); // nothing of the selection is visible


    QTextBlock block = begin.block();

    if (block.blockNumber() < m_editor->firstVisibleBlock().blockNumber() - 4)
        block = m_editor->document()->findBlockByNumber(m_editor->firstVisibleBlock().blockNumber() - 4);

    bool inSelection = false;

    QVector<QRectF> selection;

    if (begin.position() == end.position()) {
        // special case empty selections
        const QRectF blockGeometry = m_editor->blockBoundingGeometry(block);
        QTextLayout *blockLayout = block.layout();
        int pos = begin.position() - begin.block().position();
        QTextLine line = blockLayout->lineForTextPosition(pos);
        QRectF lineRect = line.naturalTextRect();
        int x = line.cursorToX(pos);
        lineRect.setLeft(x - m_borderWidth);
        lineRect.setRight(x + m_borderWidth);
        selection += lineRect.translated(blockGeometry.topLeft());
    } else {
        for (; block.isValid() && block.blockNumber() <= end.blockNumber(); block = block.next()) {
            if (! block.isVisible())
                continue;

            const QRectF blockGeometry = m_editor->blockBoundingGeometry(block);
            QTextLayout *blockLayout = block.layout();

            QTextLine line = blockLayout->lineAt(0);
            bool firstOrLastBlock = false;

            int beginChar = 0;
            if (!inSelection) {
                if (block == begin.block()) {
                    beginChar = begin.positionInBlock();
                    line = blockLayout->lineForTextPosition(beginChar);
                    firstOrLastBlock = true;
                }
                inSelection = true;
            } else {
//                while (beginChar < block.length() && document->characterAt(block.position() + beginChar).isSpace())
//                    ++beginChar;
//                if (beginChar == block.length())
//                    beginChar = 0;
            }

            int lastLine = blockLayout->lineCount()-1;
            int endChar = -1;
            if (block == end.block()) {
                endChar = end.positionInBlock();
                lastLine = blockLayout->lineForTextPosition(endChar).lineNumber();
                inSelection = false;
                firstOrLastBlock = true;
            } else {
                endChar = block.length();
                while (endChar > beginChar && document->characterAt(block.position() + endChar - 1).isSpace())
                    --endChar;
            }

            QRectF lineRect = line.naturalTextRect();
            if (beginChar < endChar) {
                lineRect.setLeft(line.cursorToX(beginChar));
                if (line.lineNumber() == lastLine)
                    lineRect.setRight(line.cursorToX(endChar));
                selection += lineRect.translated(blockGeometry.topLeft());

                for (int lineIndex = line.lineNumber()+1; lineIndex <= lastLine; ++lineIndex) {
                    line = blockLayout->lineAt(lineIndex);
                    lineRect = line.naturalTextRect();
                    if (lineIndex == lastLine)
                        lineRect.setRight(line.cursorToX(endChar));
                    selection += lineRect.translated(blockGeometry.topLeft());
                }
            } else { // empty lines
                const int emptyLineSelectionSize = 16;
                if (!firstOrLastBlock && !selection.isEmpty()) { // middle
                    lineRect.setLeft(selection.last().left());
                } else if (inSelection) { // first line
                    lineRect.setLeft(line.cursorToX(beginChar));
                } else { // last line
                    if (endChar == 0)
                        break;
                    lineRect.setLeft(line.cursorToX(endChar) - emptyLineSelectionSize);
                }
                lineRect.setRight(lineRect.left() + emptyLineSelectionSize);
                selection += lineRect.translated(blockGeometry.topLeft());
            }

            if (!inSelection)
                break;

            if (blockGeometry.translated(offset).y() > 2*viewportRect.height())
                break;
        }
    }


    if (selection.isEmpty())
        return QPainterPath();

    QVector<QPointF> points;

    const int margin = m_borderWidth/2;
    const int extra = 0;

    points += (selection.at(0).topLeft() + selection.at(0).topRight()) / 2 + QPointF(0, -margin);
    points += selection.at(0).topRight() + QPointF(margin+1, -margin);
    points += selection.at(0).bottomRight() + QPointF(margin+1, 0);


    for(int i = 1; i < selection.count()-1; ++i) {

#define MAX3(a,b,c) qMax(a, qMax(b,c))
        qreal x = MAX3(selection.at(i-1).right(),
                       selection.at(i).right(),
                       selection.at(i+1).right()) + margin;

        points += QPointF(x+1, selection.at(i).top());
        points += QPointF(x+1, selection.at(i).bottom());

    }

    points += selection.at(selection.count()-1).topRight() + QPointF(margin+1, 0);
    points += selection.at(selection.count()-1).bottomRight() + QPointF(margin+1, margin+extra);
    points += selection.at(selection.count()-1).bottomLeft() + QPointF(-margin, margin+extra);
    points += selection.at(selection.count()-1).topLeft() + QPointF(-margin, 0);

    for(int i = selection.count()-2; i > 0; --i) {
#define MIN3(a,b,c) qMin(a, qMin(b,c))
        qreal x = MIN3(selection.at(i-1).left(),
                       selection.at(i).left(),
                       selection.at(i+1).left()) - margin;

        points += QPointF(x, selection.at(i).bottom()+extra);
        points += QPointF(x, selection.at(i).top());
    }

    points += selection.at(0).bottomLeft() + QPointF(-margin, extra);
    points += selection.at(0).topLeft() + QPointF(-margin, -margin);


    QPainterPath path;
    const int corner = 4;
    path.moveTo(points.at(0));
    points += points.at(0);
    QPointF previous = points.at(0);
    for (int i = 1; i < points.size(); ++i) {
        QPointF point = points.at(i);
        if (point.y() == previous.y() && qAbs(point.x() - previous.x()) > 2*corner) {
            QPointF tmp = QPointF(previous.x() + corner * ((point.x() > previous.x())?1:-1), previous.y());
            path.quadTo(previous, tmp);
            previous = tmp;
            i--;
            continue;
        } else if (point.x() == previous.x() && qAbs(point.y() - previous.y()) > 2*corner) {
            QPointF tmp = QPointF(previous.x(), previous.y() + corner * ((point.y() > previous.y())?1:-1));
            path.quadTo(previous, tmp);
            previous = tmp;
            i--;
            continue;
        }


        QPointF target = (previous + point) / 2;
        path.quadTo(previous, target);
        previous = points.at(i);
    }
    path.closeSubpath();
    path.translate(offset);
    return path;
}
Example #21
0
int ParserExpr::calculateDegree(const QString& monome) const {
    QVector<int> exponents = getExponents(monome);
    return exponents.at(0) + exponents.at(1) + exponents.at(2);
}
Example #22
0
/*
|--------------------------------------------------------------------------------
| Método responsável pelo slot "IniciarTreinamento"
|--------------------------------------------------------------------------------
*/
void MainWindow::slotIniciarTreinamento()
{
    if(this->_lineEditNumeroEpocas->text() == ""){
        QMessageBox m;
        m.setText("Campo número de épocas está vazio.");
        m.exec();
        return;
    }

    if(this->_lineEditPrecisao->text() == ""){
        QMessageBox m;
        m.setText("Campo precisão está vazio.");
        m.exec();
        return;
    }

    if(this->_lineEditTaxaAprendizado->text() == ""){
        QMessageBox m;
        m.setText("Campo taxa de aprendizado está vazio.");
        m.exec();
        return;
    }

    if(this->_lineEditAmostraTreinamento->text() == ""){
        QMessageBox m;
        m.setText("Campo amostras de treinamento está vazio.");
        m.exec();
        return;
    }

    if(this->_lineEditSaidaDesejada->text() == ""){
        QMessageBox m;
        m.setText("Campo saídas desejadas está vazio.");
        m.exec();
        return;
    }

    if(this->_lineEditGuardarPesos->text() == ""){
        QMessageBox m;
        m.setText("Campo guardar pesos está vazio.");
        m.exec();
        return;
    }

    this->_lineEditNumeroEpocas->setEnabled(false);
    this->_lineEditPrecisao->setEnabled(false);
    this->_lineEditTaxaAprendizado->setEnabled(false);
    this->_lineEditAmostraTreinamento->setEnabled(false);
    this->_lineEditSaidaDesejada->setEnabled(false);
    this->_buttonSelecionarArquivoAmostas->setEnabled(false);
    this->_buttonSelecionarArquivoSaidas->setEnabled(false);
    this->_buttonIniciarTreinamento->setEnabled(false);
    this->_lineEditMomentum->setEnabled(false);

    /*
|--------------------------------------------------------------------------------
| Carrega Arquivo de Amostras
|--------------------------------------------------------------------------------
*/
    QString path_amostras = this->_lineEditAmostraTreinamento->text();

    QFile amostras(path_amostras);
    if(!amostras.open(QIODevice::ReadOnly)) {
        qDebug() << amostras.errorString();
        exit(0);
    }

    QTextStream in_a(&amostras);

    while(!in_a.atEnd()) {
        QString line_a = in_a.readLine();
        QStringList fields_a = line_a.split(",");

        QVector<double> amostra;

        for(int i = 0; i < fields_a.size(); i++) {
            double value_a = fields_a.at(i).toDouble();
            amostra.append(value_a);
        }

        amostras_treinamento.append(amostra);
    }

    amostras.close();

    /*
|--------------------------------------------------------------------------------
| Carrega Arquivo de Saidas
|--------------------------------------------------------------------------------
*/
    QString path_saidas = this->_lineEditSaidaDesejada->text();

    QFile saidas(path_saidas);
    if(!saidas.open(QIODevice::ReadOnly)) {
        qDebug() << saidas.errorString();
        exit(0);
    }

    QTextStream in_s(&saidas);

    while(!in_s.atEnd()) {
        QString line_s = in_s.readLine();
        QStringList fields_s = line_s.split(",");
        QVector<double> saida;

        for(int i = 0; i < fields_s.size(); i++) {
            double value_s = fields_s.at(i).toDouble();
            saida.append(value_s);
        }

        saidas_desejada.append(saida);
    }

    saidas.close();
    /*
|--------------------------------------------------------------------------------
| Treinamento
|--------------------------------------------------------------------------------
*/
    double precisao = this->_lineEditPrecisao->text().toDouble(); // pega precisao informada na interface
    double aprendizado = this->_lineEditTaxaAprendizado->text().toDouble(); // pega a taxa de aprendizado infomada da interface
    int numepocas = this->_lineEditNumeroEpocas->text().toInt(); // pega o numero de épocas informada na interaface
    double MOMENTUM = this->_lineEditMomentum->text().toDouble();           // Termo de momentum.

    QVector<double> gepocas(numepocas), gerro(numepocas);// vetores que guardam a epoca e seu respectivo erro

    int epocas = 0;
    double erro_medio_quadratico= 0;
    double erro_quadratico = 0;
    double somatorio = 0;
    int funcao = 0;

    if(this->_CB_funcaoL->isChecked()){
        funcao = 0;
        this->_CB_funcaoTH->setChecked(false);
    }
    if(this->_CB_funcaoTH->isChecked()){
        funcao = 1;
        this->_CB_funcaoL->setChecked(false);
    }

    zeraPesos(1);
    zeraPesos(2);

    zeraVetoresNeuronios(1);
    zeraVetoresNeuronios(2);

    randomizaPesos(1);
    randomizaPesos(2);




    // pesos randomizados para a camada 1.
    qDebug()  <<" pesos randomizados para a camada 1";
    for (int j = 0; j < (NUM_NEURONIOS_CAMADA_UM*NUM_ENTRADAS); j++)
    {
        qDebug() <<w1[j] ;
    }


    // pesos randomizados para a camada 2.
    qDebug()  <<" pesos randomizados para a camada 2";
    for (int j = 0; j < (NUM_NEURONIOS_CAMADA_DOIS*NUM_NEURONIOS_CAMADA_UM); j++)
    {
        qDebug() <<w2[j] ;
    }


    qDebug()  <<"**************************** Inico Treinamento ****************************";

    do{

        // Propaga os k padrıes pela rede.
        for (int k = 0; k < amostras_treinamento.size(); k++)
        {
            qDebug() <<"calc c1";
            //C·lculo para camada C1.
            int n = 0;
            for (int j = 0; j < NUM_NEURONIOS_CAMADA_UM; j++)
            {
                somatorio = 0;
                for (int i = 0; i < NUM_ENTRADAS; i++)
                {
                    somatorio += w1[n] * amostras_treinamento.at(k).at(i);//amostras_treinamento.at(k);
                    n += 1;
                }
                Entrada_I1[j] = somatorio;
                saida_y1[j] = FuncaoAtivacao(Entrada_I1[j],funcao,1.0);
            }
            qDebug() <<"calc c2";
            //C·lculo para camada C2.
            n = 0;
            for (int j = 0; j < NUM_NEURONIOS_CAMADA_DOIS; j++)
            {
                somatorio = 0;
                for (int i = 0; i < NUM_NEURONIOS_CAMADA_UM; i++)
                {
                    somatorio += w2[n] * saida_y1[i];
                    n += 1;
                }
                Entrada_I2[j] = somatorio;
                saida_y2[j] = FuncaoAtivacao(Entrada_I2[j],funcao,1.0);
            }

            //********************* C·lculo do Erro MÈdio Quadr·tico ************************
            qDebug() <<"Calculo do Erro Quadratico";
            //Calculo do Erro Quadratico.
            erro_quadratico = 0;
            for(int j = 0; j < NUM_NEURONIOS_CAMADA_DOIS; j++)
            {
                erro_quadratico += pow((saidas_desejada[k][j] - saida_y2[j]),2);
            }

            //Calculo do Erro Medio Quadratico (Criterio de Parada).
            erro_medio_quadratico += (0.5 * erro_quadratico);


            //**************************** Retropropagacao do Erro **************************

            //Calculo do erro para camada 2.
            for (int i = 0; i < NUM_NEURONIOS_CAMADA_DOIS; i++)
            {
                erro_camada2[i] = (saidas_desejada[k][i] - saida_y2[i]) * derivada(Entrada_I2[i],funcao,1.0);
            }

            //Atualizacao dos pesos para camada 2.
            for (int i = 0; i < NUM_NEURONIOS_CAMADA_UM; i++)
            {
                n = 0;
                for (int j = 0; j < NUM_NEURONIOS_CAMADA_DOIS; j++)
                {
                    dw2[n + i] = aprendizado * saida_y1[i] * erro_camada2[j] + (MOMENTUM * dw2[n + i]);
                    w2[n + i] = w2[n + i] + dw2[n + i];
                    n += NUM_NEURONIOS_CAMADA_UM;
                }
            }

            //Calculo do erro para camada 1.
            for (int i = 0; i < NUM_NEURONIOS_CAMADA_UM; i++)
            {
                n = 0;
                somatorio = 0;
                for (int j = 0; j < NUM_NEURONIOS_CAMADA_DOIS; j++)
                {
                    somatorio += (erro_camada2[j] * w2[n + i]);
                    n += NUM_NEURONIOS_CAMADA_UM;
                }
                erro_camada1[i] = somatorio * derivada(Entrada_I1[i],funcao,1.0);
            }

            //Atualizacao dos pesos para camada 1.
            for (int i = 0; i < NUM_ENTRADAS; i++)
            {
                n = 0;
                for (int j = 0; j < NUM_NEURONIOS_CAMADA_UM; j++)
                {
                    dw1[n + i] = aprendizado * amostras_treinamento.at(k).at(i) * erro_camada1[j] + (MOMENTUM * dw1[n + i]);
                    w1[n + i] = w1[n + i] + dw1[n + i];
                    n += NUM_ENTRADAS;
                }
            }
        }

        // C·lculo do erro mÈdio quadr·tico da Època de treinamento.
        erro_medio_quadratico = (1.0 / amostras_treinamento.size()) * erro_medio_quadratico;

        gerro.append(erro_medio_quadratico);
        gepocas.append(epocas);

        epocas++;

       // qDebug() << erro_medio_quadratico;
        //qDebug() << epocas;

        erro_medio_quadratico = 0;


    } while(epocas < numepocas ||erro_medio_quadratico >= precisao);
    qDebug()  <<"**************************** Fim Treinamento ****************************";
    /*
|--------------------------------------------------------------------------------
| Gráfico
|--------------------------------------------------------------------------------
*/

    this->_chart->graph(0)->setData(gepocas, gerro);
    this->_chart->xAxis->setLabel("CONTAGEM DAS ÉPOCAS");
    this->_chart->yAxis->setLabel("ERRO");
    this->_chart->xAxis->setRange(0, numepocas);
    this->_chart->yAxis->setRange(0, 1.5);
    this->_chart->replot();

    /*
|--------------------------------------------------------------------------------
| Habilitar Botões
|--------------------------------------------------------------------------------
*/
    this->_lineEditNumeroEpocas->setEnabled(true);
    this->_lineEditPrecisao->setEnabled(true);
    this->_lineEditTaxaAprendizado->setEnabled(true);
    this->_lineEditAmostraTreinamento->setEnabled(true);
    this->_lineEditSaidaDesejada->setEnabled(true);
    this->_buttonSelecionarArquivoAmostas->setEnabled(true);
    this->_buttonSelecionarArquivoSaidas->setEnabled(true);
    this->_buttonIniciarTreinamento->setEnabled(true);
    this->_buttonGuardarPesos->setEnabled(true);
    this->_lineEditMomentum->setEnabled(true);

}
Example #23
0
void MsScWriter::note(const QString pitch, const QVector<Bww::BeamType> beamList,
                      const QString type, const int dots,
                      bool tieStart, bool /*TODO tieStop */,
                      StartStop triplet,
                      bool grace)
      {
      qDebug() << "MsScWriter::note()"
               << "type:" << type
               << "dots:" << dots
               << "grace" << grace
      ;

      if (!stepAlterOctMap.contains(pitch)
          || !typeMap.contains(type)) {
            // TODO: error message
            return;
            }
      StepAlterOct sao = stepAlterOctMap.value(pitch);

      int ticks = 4 * Ms::MScore::division / type.toInt();
      if (dots) ticks = 3 * ticks / 2;
      qDebug() << "ticks:" << ticks;
      Ms::TDuration durationType(Ms::TDuration::DurationType::V_INVALID);
      durationType.setVal(ticks);
      qDebug() << "duration:" << durationType.name();
      if (triplet != ST_NONE) ticks = 2 * ticks / 3;

      Ms::Beam::Mode bm  = (beamList.at(0) == Bww::BM_BEGIN) ? Ms::Beam::Mode::BEGIN : Ms::Beam::Mode::AUTO;
      Ms::Direction sd = Ms::Direction::AUTO;

      // create chord
      Ms::Chord* cr = new Ms::Chord(score);
      //ws cr->setTick(tick);
      cr->setBeamMode(bm);
      cr->setTrack(0);
      if (grace) {
            cr->setNoteType(Ms::NoteType::GRACE32);
            cr->setDurationType(Ms::TDuration::DurationType::V_32ND);
            sd = Ms::Direction::UP;
            }
      else {
            if (durationType.type() == Ms::TDuration::DurationType::V_INVALID)
                  durationType.setType(Ms::TDuration::DurationType::V_QUARTER);
            cr->setDurationType(durationType);
            sd = Ms::Direction::DOWN;
            }
      cr->setDuration(durationType.fraction());
      cr->setDots(dots);
      cr->setStemDirection(sd);
      // add note to chord
      Ms::Note* note = new Ms::Note(score);
      note->setTrack(0);
      xmlSetPitch(note, sao.s.toLatin1(), sao.a, sao.o);
      if (tieStart) {
            Ms::Tie* tie = new Ms::Tie(score);
            note->setTieFor(tie);
            tie->setStartNote(note);
            tie->setTrack(0);
            }
      cr->add(note);
      // add chord to measure
      if (!grace) {
            Ms::Segment* s = currentMeasure->getSegment(Ms::Segment::Type::ChordRest, tick);
            s->add(cr);
            if (!currentGraceNotes.isEmpty()) {
                  for (int i = currentGraceNotes.size() - 1; i >=0; i--)
                        cr->add(currentGraceNotes.at(i));
                  currentGraceNotes.clear();
                  }
            doTriplet(cr, triplet);
            int tickBefore = tick;
            tick += ticks;
            Ms::Fraction nl(Ms::Fraction::fromTicks(tick - currentMeasure->tick()));
            currentMeasure->setLen(nl);
            qDebug() << "MsScWriter::note()"
                     << "tickBefore:" << tickBefore
                     << "tick:" << tick
                     << "nl:" << nl.print()
            ;
            }
      else {
            currentGraceNotes.append(cr);
            }
      }
Example #24
0
/*!
    \reimp
*/
void QBoxLayout::setGeometry(const QRect &r)
{
    Q_D(QBoxLayout);
    if (d->dirty || r != geometry()) {
        QRect oldRect = geometry();
        QLayout::setGeometry(r);
        if (d->dirty)
            d->setupGeom();
        QRect cr = alignment() ? alignmentRect(r) : r;

        int left, top, right, bottom;
        d->effectiveMargins(&left, &top, &right, &bottom);
        QRect s(cr.x() + left, cr.y() + top,
                cr.width() - (left + right),
                cr.height() - (top + bottom));

        QVector<QLayoutStruct> a = d->geomArray;
        int pos = horz(d->dir) ? s.x() : s.y();
        int space = horz(d->dir) ? s.width() : s.height();
        int n = a.count();
        if (d->hasHfw && !horz(d->dir)) {
            for (int i = 0; i < n; i++) {
                QBoxLayoutItem *box = d->list.at(i);
                if (box->item->hasHeightForWidth()) {
                    int width = qBound(box->item->minimumSize().width(), s.width(), box->item->maximumSize().width());
                    a[i].sizeHint = a[i].minimumSize =
                                    box->item->heightForWidth(width);
                }
            }
        }

        Direction visualDir = d->dir;
        QWidget *parent = parentWidget();
        if (parent && parent->isRightToLeft()) {
            if (d->dir == LeftToRight)
                visualDir = RightToLeft;
            else if (d->dir == RightToLeft)
                visualDir = LeftToRight;
        }

        qGeomCalc(a, 0, n, pos, space);

        bool reverse = (horz(visualDir)
                        ? ((r.right() > oldRect.right()) != (visualDir == RightToLeft))
                        : r.bottom() > oldRect.bottom());
        for (int j = 0; j < n; j++) {
            int i = reverse ? n-j-1 : j;
            QBoxLayoutItem *box = d->list.at(i);

            switch (visualDir) {
            case LeftToRight:
                box->item->setGeometry(QRect(a.at(i).pos, s.y(), a.at(i).size, s.height()));
                break;
            case RightToLeft:
                box->item->setGeometry(QRect(s.left() + s.right() - a.at(i).pos - a.at(i).size + 1,
                                             s.y(), a.at(i).size, s.height()));
                break;
            case TopToBottom:
                box->item->setGeometry(QRect(s.x(), a.at(i).pos, s.width(), a.at(i).size));
                break;
            case BottomToTop:
                box->item->setGeometry(QRect(s.x(),
                                             s.top() + s.bottom() - a.at(i).pos - a.at(i).size + 1,
                                             s.width(), a.at(i).size));
            }
        }
    }
}
void QWindowsFileSystemWatcherEngine::run()
{
    QMutexLocker locker(&mutex);
    forever {
        QVector<HANDLE> handlesCopy = handles;
        locker.unlock();
        // qDebug() << "QWindowsFileSystemWatcherEngine: waiting on" << handlesCopy.count() << "handles";
        DWORD r = WaitForMultipleObjects(handlesCopy.count(), handlesCopy.constData(), false, INFINITE);
        locker.relock();
        do {
            if (r == WAIT_OBJECT_0) {
                int m = msg;
                msg = 0;
                if (m == 'q') {
                    // qDebug() << "thread told to quit";
                    return;
                }
                if (m != '@')  {
                    qDebug("QWindowsFileSystemWatcherEngine: unknown message '%c' send to thread", char(m));
                }
                break;
            } else if (r > WAIT_OBJECT_0 && r < WAIT_OBJECT_0 + uint(handlesCopy.count())) {
                int at = r - WAIT_OBJECT_0;
                Q_ASSERT(at < handlesCopy.count());
                HANDLE handle = handlesCopy.at(at);

                // When removing a path, FindCloseChangeNotification might actually fire a notification
                // for some reason, so we must check if the handle exist in the handles vector
                if (handles.contains(handle)) {
                    // qDebug("Acknowledged handle: %d, %p", at, handle);
                    if (!FindNextChangeNotification(handle)) {
                        qErrnoWarning("QFileSystemWatcher: FindNextChangeNotification failed");
                    }

                    QHash<QString, PathInfo> &h = pathInfoForHandle[handle];
                    QMutableHashIterator<QString, PathInfo> it(h);
                    while (it.hasNext()) {
                        QHash<QString, PathInfo>::iterator x = it.next();
                        QString absolutePath = x.value().absolutePath;
                        QFileInfo fileInfo(x.value().path);
                        // qDebug() << "checking" << x.key();
                        if (!fileInfo.exists()) {
                            // qDebug() << x.key() << "removed!";
                            if (x.value().isDir)
                                emit directoryChanged(x.value().path, true);
                            else
                                emit fileChanged(x.value().path, true);
                            h.erase(x);

                            // close the notification handle if the directory has been removed
                            if (h.isEmpty()) {
                                // qDebug() << "Thread closing handle" << handle;
                                FindCloseChangeNotification(handle);    // This one might generate a notification

                                int indexOfHandle = handles.indexOf(handle);
                                Q_ASSERT(indexOfHandle != -1);
                                handles.remove(indexOfHandle);

                                handleForDir.remove(absolutePath);
                                // h is now invalid
                            }
                        } else if (x.value() != fileInfo) {
                            // qDebug() << x.key() << "changed!";
                            if (x.value().isDir)
                                emit directoryChanged(x.value().path, false);
                            else
                                emit fileChanged(x.value().path, false);
                            x.value() = fileInfo;
                        }
                    }
                }
            } else {
                // qErrnoWarning("QFileSystemWatcher: error while waiting for change notification");
                break;  // avoid endless loop
            }
            handlesCopy = handles;
            r = WaitForMultipleObjects(handlesCopy.count(), handlesCopy.constData(), false, 0);
        } while (r != WAIT_TIMEOUT);
    }
}
Example #26
0
/*forbids cells so no block is put there to avoid blocking the a path*/
void kmagnetGenerator::forbidcells(int num, QVector<int> &positions, Moves::Move m)
{
    int i=0;
    int vecnum;
    int banpos=0;
    int currentpos=m_scene->getCurrentCell();
    bool finished=false;
    if (m==Moves::UP)
    {
        banpos=currentpos-columns;
        if (banpos>=0)
            forbiddenPos.append(banpos);
        for (i=0;i < positions.size() && !finished ;i++)
        {
            vecnum=positions.at(i);
            if (vecnum>=num) {
                forbiddenPos.append(vecnum);
                if (vecnum==num)finished=true;
            }
        }
    }
    else if (m==Moves::DOWN)
    {
        finished=false;
        banpos= currentpos+columns;
        if (banpos<=numcells) forbiddenPos.append(banpos);
        for (i=positions.size()-1; i>=0 && !finished ;i--)
        {
            vecnum=positions.at(i);
            if (vecnum<=num) {
                forbiddenPos.append(vecnum);
                if (vecnum==num)finished=true;
            }
        }
    }
    else if (m==Moves::LEFT)
    {
        finished=false;
        if ((currentpos % columns)!=0)
            forbiddenPos.append(currentpos-1);
        for (i=0; i < positions.size() && !finished;i++)
        {
            vecnum=positions.at(i);
            if (vecnum>=num) {
                forbiddenPos.append(vecnum);
                if (vecnum==num)finished=true;
            }
        }
    }
    else if (m==Moves::RIGHT)
    {
        finished=false;
        if ((currentpos % columns)!=9)
            forbiddenPos.append(currentpos+1);
        for (i=positions.size()-1; i>=0 && !finished ;i--)
        {
            vecnum=positions.at(i);
            if (vecnum<=num) {
                forbiddenPos.append(vecnum);
                if (vecnum==num)finished=true;
            }
        }
    }
}
Example #27
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;
    }
}
QString CSV_Helper::Get_Value_At_Index(int index, const QString &line) {
    assert(index >= 0);
    QVector<QString> elements = this->Get_CSV_Elements_From_Line_As_Vector(line);
    assert(elements.length() <= index);
    return elements.at(index);
}
Example #29
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;
}
Example #30
0
void SINWAV::getSINWAV (Q3PtrList<PlotLine> &pll)
{
  // Ehler's sine wave

  PlotLine *Price = new PlotLine;

  int i = 0;

  // price = (h + l) / 2
  for (i = 0; i < (int) data->count(); i++)
    Price->append((data->getHigh(i) + data->getLow(i)) / 2);

  //! VERSION 2

  QVector<double> *smooth = new QVector<double>(Price->getSize());
  smooth->fill(0.0);
  QVector<double> *detrender = new QVector<double>(Price->getSize());
  detrender->fill(0.0);
  QVector<double> *period = new QVector<double>(Price->getSize());
  period->fill(0.0);
  QVector<double> *Q1 = new QVector<double>(Price->getSize());
  Q1->fill(0.0);
  QVector<double> *I1 = new QVector<double>(Price->getSize());
  I1->fill(0.0);
  QVector<double> *jI = new QVector<double>(Price->getSize());
  jI->fill(0.0);
  QVector<double> *jQ = new QVector<double>(Price->getSize());
  jQ->fill(0.0);
  QVector<double> *I2 = new QVector<double>(Price->getSize());
  I2->fill(0.0);
  QVector<double> *Q2 = new QVector<double>(Price->getSize());
  Q2->fill(0.0);
  QVector<double> *Re = new QVector<double>(Price->getSize());
  Re->fill(0.0);
  QVector<double> *Im = new QVector<double>(Price->getSize());
  Im->fill(0.0);
  QVector<double> *SmoothPrice = new QVector<double>(Price->getSize());
  SmoothPrice->fill(0.0);
  QVector<double> *DCPhase = new QVector<double>(Price->getSize());
  DCPhase->fill(0.0);

  PlotLine *out1 = new PlotLine;
  PlotLine *out2 = new PlotLine;

  double SmoothPeriod = 0;
  double DCPeriod = 0;

  for (i = 6; i< Price->getSize(); i++)
  {
    // Weighted price
    (*smooth)[i] = ( 4 * Price->getData(i) + 3 * Price->getData(i-1) +
		      2 * Price->getData(i-2) +  Price->getData(i-3)) /10.0;

    (*detrender)[i] = (0.0962 * smooth->at(i) + 0.5769 * smooth->at(i-2) -
			0.5769 * smooth->at(i-4) - 0.0962 * smooth->at(i-6)) *
		        (0.075 * period->at(i-1) + 0.54);

    // Compute InPhase and Quadrature components
    (*Q1)[i] = (0.0962 * detrender->at(i) + 0.5769 * detrender->at(i-2) -
		 0.5769 * detrender->at(i-4) - 0.0962 * detrender->at(i-6)) *
		 (0.075 * period->at(i-1) + 0.54);
    (*I1)[i] = detrender->at(i-3);

    //Advance the phase of I1 and Q1 by 90 degrees
    (*jI)[i] = (0.0962 * I1->at(i) + 0.5769 * I1->at(i-2) -
		 0.5769 * I1->at(i-4) - 0.0962 * I1->at(i-6)) *
		 (0.075 * period->at(i-1) + 0.54);

    (*Q1)[i] = (0.0962 * Q1->at(i) + 0.5769 * Q1->at(i-2) -
		 0.5769 * Q1->at(i-4) - 0.0962 * Q1->at(i-6)) *
		 (0.075 * period->at(i-1) + 0.54);

    // Phasor addition for 3-bar averaging
    (*I2)[i] = I1->at(i) - jQ->at(i);
    (*Q2)[i] = Q1->at(i) + jI->at(i);

    // Smooth the I and Q components before applying the discriminator
    (*I2)[i] = 0.2 * I2->at(i) + 0.8 * I2->at(i-1);
    (*Q2)[i] = 0.2 * Q2->at(i) + 0.8 * Q2->at(i-1);

    // Homodyne Discriminator
    (*Re)[i] = I2->at(i) * I2->at(i-1) + Q2->at(i) * Q2->at(i-1);
    (*Im)[i] = I2->at(i) * Q2->at(i-1) - Q2->at(i) * I2->at(i-1);
    (*Re)[i] = 0.2 * Re->at(i) + 0.8 * Re->at(i-1);
    (*Im)[i] = 0.2 * Im->at(i) + 0.8 * Im->at(i-1);
    if (Im->at(i) != 0 && Re->at(i) != 0 )
      (*period)[i] = 360/(atan(Im->at(i) / Re->at(i)) * (180/PI));
    if (period->at(i) > 1.5 * period->at(i-1))
      (*period)[i] = 1.5 * period->at(i-1);
    if (period->at(i) < 0.67 * period->at(i-1))
      (*period)[i] = 0.67 * period->at(i-1);
    if (period->at(i) < 6)
      (*period)[i] = 6;
    if (period->at(i) > 50)
      (*period)[i] = 50;

    (*period)[i] = 0.2 * period->at(i) + 0.8 * period->at(i-1);

    SmoothPeriod = 0.33 * period->at(i) + 0.67 * SmoothPeriod;

    // Compute Dominant CyclePhase
    (*SmoothPrice)[i] = (4 * Price->getData(i) + 3 * Price->getData(i-1) +
			  2 * Price->getData(i-2) +  Price->getData(i-3)) /10.0;

    DCPeriod = (int)(SmoothPeriod + 0.5);

    double RealPart = 0;
    double ImagPart = 0;
    int j = 0;

    if (i >= (int)DCPeriod)
    {
      for (j = 0; j < (int)DCPeriod; j++)
      {
        RealPart = RealPart + sin((360 * (double)j / DCPeriod) * (PI/180)) * (SmoothPrice->at(i - j));
	ImagPart = ImagPart + cos((360 * (double)j / DCPeriod) * (PI/180)) * (SmoothPrice->at(i - j));
      }
    }

    if (fabs(ImagPart) > 0.001)
      (*DCPhase)[i] = atan(RealPart / ImagPart) * (180/PI);

    if( fabs(ImagPart) <= 0.001 )
      (*DCPhase)[i] = 90.0 * sin(RealPart * (PI/180));

    (*DCPhase)[i] = DCPhase->at(i) + 90.0;

    // Compensate for one bar lag of the Weighted Moving Average
    (*DCPhase)[i] = DCPhase->at(i) + 360.0 / SmoothPeriod;

    if (ImagPart < 0)
      (*DCPhase)[i] = DCPhase->at(i) + 180.0;

    if (DCPhase->at(i) > 315.0)
      (*DCPhase)[i] = DCPhase->at(i) - 360.0;

    // we're done....
    out1->append(sin(DCPhase->at(i) * (PI/180)));
    out2->append(sin((DCPhase->at(i) + 45.0) * (PI/180)));
  }

  delete smooth;
  delete detrender;
  delete period;
  delete Q1;
  delete I1;
  delete jI;
  delete jQ;
  delete I2;
  delete Q2;
  delete Re;
  delete Im;
  delete SmoothPrice;
  delete DCPhase;
  delete Price;

  out1->setColor(colorSin);
  out1->setLabel(labelSin);
  out1->setType(lineTypeSin);
  pll.append(out1);

  out2->setColor(colorLead);
  out2->setLabel(labelLead);
  out2->setType(lineTypeLead);
  pll.append(out2);
}