void Exchange_Bitstamp::filterAvailableUSDAmountValue(double *amount)
{
	double decValue=mainWindow.getValidDoubleForPercision((*amount)*mainWindow.floatFee,baseValues.currentPair.priceDecimals,false);
	decValue+=qPow(0.1,qMax(baseValues.currentPair.priceDecimals,1));
	*amount=mainWindow.getValidDoubleForPercision((*amount)-decValue,baseValues.currentPair.currBDecimals,false);
}
Пример #2
0
void ImageView::wheelEvent(QWheelEvent *event)
{
    qreal factor = qPow(Constants::DEFAULT_SCALE_FACTOR, event->delta() / 240.0);
    doScale(factor);
    event->accept();
}
Пример #3
0
qreal Curve::calcYDerivative(qreal t)
{
	return (t * t + 2 * t - 1) / qPow(t + 1, 2.);
}
Пример #4
0
void MainWindow::tick()
{
    if((pig_count==0&&bird_count==6) || score==33000)
    {
        qDebug() << "pig_count : " << pig_count;
        qDebug() << "bird_count : " << bird_count;
        qDebug() << "score : " << score;
        showResult();
    }
    ui->lcdNumber->display(score);
    ui->lcdNumber_2->display(pig_count);
    ui->lcdNumber_3->display(6-bird_count);
    if(shot)
    {
        CD = (*Bit)->available;
        b2Vec2 speed = (*Bit)->Body->GetLinearVelocity();
        VB = qSqrt(qPow(speed.x,2)+qPow(speed.y,2));
        b2Vec2 X = (*Bit)->Body->GetPosition();;
        if((X.y>120 || X.x<-20) || X.x>100)
            outer = true;
        if((VB==0 || outer) && bird_count == 2)
        {
            bird2 = new Bird(2,6.8f, 10.7f,BIRD_DENSITY, BIRD_RADIUS, &timer, QPixmap(":/bird/img/Angry Birds Seasons/angry-bird-yellow-icon.png"), world, scene);
            BIRD.push_back(bird2);
            delete (*Bit);
            BIRD.erase(Bit);
            shot = false;
            newed = true;
            outer = false;
        }
        else if((VB==0 || outer) && bird_count == 3)
        {
            bird3 = new Bird(3,6.8f, 10.7f,BIRD_DENSITY*4, 1.5, &timer, QPixmap(":/bird/img/Angry Birds Seasons/BLOCK_STEEL_BALL.png"), world, scene);
            BIRD.push_back(bird3);
            delete (*Bit);
            BIRD.erase(Bit);
            shot = false;
            newed = true;
            outer = false;
        }
        else if((VB==0 || outer) && bird_count == 4)
        {
            bird4 = new Bird(4,6.8f, 10.7f,BIRD_DENSITY, BIRD_RADIUS*1.75, &timer, QPixmap(":/bird/img/Angry Birds Seasons/BIRD_GREY_YELL.png"), world, scene);
            BIRD.push_back(bird4);
            delete (*Bit);
            BIRD.erase(Bit);
            shot = false;
            newed = true;
            outer = false;
        }
        else if((VB==0 || outer) && bird_count == 5)
        {
            bird5 = new Bird(5,7.1f, 10.9f,BIRD_DENSITY, BIRD_RADIUS*2, &timer, QPixmap(":/bird/img/Angry Birds Seasons/TA.png"), world, scene);
            BIRD.push_back(bird5);
            delete (*Bit);
            BIRD.erase(Bit);
            shot = false;
            newed = true;
            outer = false;
        }
        else if((VB==0 || outer) && bird_count == 6)
        {
            bird6 = new Bird(6,6.8f, 10.7f,BIRD_DENSITY, BIRD_RADIUS, &timer, QPixmap(""), world, scene);
            BIRD.push_back(bird6);
            delete (*Bit);
            BIRD.erase(Bit);
            shot = false;
            newed = true;
            outer = false;
            showResult();
        }
    }
    for(it = WOOD.begin(); it!= WOOD.end(); ++it)
    {
        if((*it)->death)
        {
            delete (*it);
            WOOD.erase(it);
            score += 2000;
            //qDebug() << score;
        }
    }
    for(it = PIG.begin(); it!= PIG.end(); ++it)
    {
        if((*it)->death)
        {
            delete (*it);
            PIG.erase(it);
            score += 5000;
            --pig_count;
            //qDebug() << score;
        }
    }
    world->Step(1.0/60.0, 6, 2);
    scene->update();
}
Пример #5
0
QLineF item_rectangles::snapLine(QLineF mouseLine, QSizeF Box)
{
    qreal a = mouseLine.angle();
    qreal relA = QLineF(0,0, Box.width(), -Box.height()).angle();
    qreal tarA = 0;

    bool isDiagonal=false;
    bool isVertical=false;

    if(a == 0)
    {
        tarA = a;
        goto skipAngleCalculate;
    }
    else if(a == 90)
    {
        tarA = a;
        isVertical=true;
        goto skipAngleCalculate;
    }
    else if(a == 180)
    {
        tarA = a;
        goto skipAngleCalculate;
    }
    else if(a == 270)
    {
        tarA = a;
        isVertical=true;
        goto skipAngleCalculate;
    }

    //Calculating target angle
    if(a <= 90){
        if(a < relA/2){
            tarA = 0;
        }else if(a <= 90-(90-relA)/2 ){
            tarA = relA;
            isDiagonal=true;
        }else{
            tarA = 90;
            isVertical=true;
        }
    }else if(a <= 180){
        if(a <= 90+(90-relA)/2 ){
            tarA = 90;
            isVertical=true;
        }else if(a <= 180-relA/2 ){
            tarA = 180-relA;
            isDiagonal=true;
        }else{
            tarA = 180;
        }
    }else if(a <= 270){
        if(a < 180+(relA/2)){
            tarA = 180;
        }else if(a <= 270-(90-relA)/2){
            tarA = 180+relA;
            isDiagonal=true;
        }else{
            tarA = 270;
            isVertical=true;
        }
    }else{
        if(a <= 270+(90-relA)/2 ){
            tarA = 270;
            isVertical=true;
        }else if(a < 360-relA/2){
            tarA = 360-relA;
            isDiagonal=true;
        }else{
            tarA = 360;
        }
    }


    skipAngleCalculate:

    qreal diagonalSize = qSqrt( qPow(Box.height(),2) + qPow(Box.width(),2) ); //get box diagonal size
    qreal Lenght = mouseLine.length() -
            ((isDiagonal)? qRound(mouseLine.length())%qRound(diagonalSize)   //Diagonal
            : (isVertical ? qRound(mouseLine.length())%qRound(Box.height()): //Vertical
              qRound(mouseLine.length())%qRound(Box.width()) ) );            //Horizontal

    return QLineF::fromPolar(Lenght,tarA).translated(mouseLine.p1());;
}
Пример #6
0
static inline QwtInterval qwtPowInterval( double base, const QwtInterval &interval )
{
    return QwtInterval( qPow( base, interval.minValue() ),
            qPow( base, interval.maxValue() ) );
}
Пример #7
0
bool MainWindow::eventFilter(QObject *, QEvent *event)
{
    if(pressed && event->type() == QEvent::MouseButtonRelease)
    {
        arrow->setVisible(false);
        Force_pos = static_cast<QMouseEvent*>(event)->pos();
        if(pressed && bird_count!=3 && bird_count!=5)
            shootbird->play();
        pressed = false;
        b2Vec2 linearV = b2Vec2((clicked_point.x()-Force_pos.x())/15,(Force_pos.y()-clicked_point.y())/15);
        if(bird_count == 1)
        {
            bird1->setLinearVelocity(linearV);
            bird1->Body->SetGravityScale(1);
            ++bird_count;
            shot = true;
            skill = true;
            /*BIRD.push_back(bird1);
            Bit = BIRD.begin();*/
            newed = false;
        }
        else if(bird_count == 2 && newed)
        {
            bird2->setLinearVelocity(linearV);
            bird2->Body->SetGravityScale(1);
            ++bird_count;
            shot = true;
            skill = true;
            //BIRD.push_back(bird2);
            //++Bit;
            newed = false;
        }
        else if(bird_count == 3 && newed)
        {
            bird3->setLinearVelocity(linearV);
            bird3->Body->SetGravityScale(1);
            ++bird_count;
            shot = true;
            skill = true;
            //BIRD.push_back(bird3);
            //++Bit;
            newed = false;
        }
        else if(bird_count == 4 && newed)
        {
            bird4->setLinearVelocity(linearV);
            bird4->Body->SetGravityScale(1);
            ++bird_count;
            shot = true;
            skill = true;
            //BIRD.push_back(bird4);
            //++Bit;
            newed = false;
        }
        else if(bird_count == 5 && newed)
        {
            bird5->setLinearVelocity(linearV);
            bird5->Body->SetGravityScale(1);
            ++bird_count;
            shot = true;
            skill = true;
            //BIRD.push_back(bird5);
            //++Bit;
            newed = false;
        }
    }
    else if(event->type() == QEvent::MouseMove)
    {
        //Force_pos = static_cast<QMouseEvent*>(event)->pos();
        if(pressed && !BIRD.empty() && !shot && VB == 0)
        {
            //qDebug() << "ARROW!";
            QPointF temp = static_cast<QMouseEvent*>(event)->pos();
            arrow->resetTransform();
            arrow->setPos(QPointF(50, 400));
            arrow->setRotation(qAtan2(-temp.y()+clicked_point.y(), -temp.x()+clicked_point.x())*180/pi);
            arrow->setScale(qSqrt(qPow(temp.y()-clicked_point.y(), 2) + qPow(temp.x()-clicked_point.x(), 2))/300);
            arrow->setVisible(true);
        }
    }
    return false;
}
Пример #8
0
void QAGC::setFixedGain(float gain) {

    mutex.lock();
    m_gainFix = qPow(10.0, gain/20.0);
    mutex.unlock();
}
Пример #9
0
void OpenAL::setInputGain(qreal dB)
{
    gain = qBound(minInGain, dB, maxInGain);
    gainFactor = qPow(10.0, (gain / 20.0));
}
Пример #10
0
void QAGC::setGainTop(float gain) {

    mutex.lock();
    m_gainTop = qPow(10.0, gain/20.0);
    mutex.unlock();
}
Пример #11
0
void QAGC::setGainBottom(float gain) {

    mutex.lock();
    m_gainBottom = qPow(10.0, gain/20.0);
    mutex.unlock();
}
QgsRasterBlock * QgsBrightnessContrastFilter::block( int bandNo, QgsRectangle  const & extent, int width, int height )
{
  Q_UNUSED( bandNo );
  QgsDebugMsg( QString( "width = %1 height = %2 extent = %3" ).arg( width ).arg( height ).arg( extent.toString() ) );

  QgsRasterBlock *outputBlock = new QgsRasterBlock();
  if ( !mInput )
  {
    return outputBlock;
  }

  // At this moment we know that we read rendered image
  int bandNumber = 1;
  QgsRasterBlock *inputBlock = mInput->block( bandNumber, extent, width, height );
  if ( !inputBlock || inputBlock->isEmpty() )
  {
    QgsDebugMsg( "No raster data!" );
    delete inputBlock;
    return outputBlock;
  }

  if ( mBrightness == 0 && mContrast == 0 )
  {
    QgsDebugMsg( "No brightness changes." );
    delete outputBlock;
    return inputBlock;
  }

  if ( !outputBlock->reset( QGis::ARGB32_Premultiplied, width, height ) )
  {
    delete inputBlock;
    return outputBlock;
  }

  // adjust image
  QRgb myNoDataColor = qRgba( 0, 0, 0, 0 );
  QRgb myColor;

  int r, g, b, alpha;
  double f = qPow(( mContrast + 100 ) / 100.0, 2 );

  for ( qgssize i = 0; i < ( qgssize )width*height; i++ )
  {
    if ( inputBlock->color( i ) == myNoDataColor )
    {
      outputBlock->setColor( i, myNoDataColor );
      continue;
    }

    myColor = inputBlock->color( i );
    alpha = qAlpha( myColor );

    r = adjustColorComponent( qRed( myColor ), alpha, mBrightness, f );
    g = adjustColorComponent( qGreen( myColor ), alpha, mBrightness, f );
    b = adjustColorComponent( qBlue( myColor ), alpha, mBrightness, f );

    outputBlock->setColor( i, qRgba( r, g, b, alpha ) );
  }

  delete inputBlock;
  return outputBlock;
}
Пример #13
0
qreal MyWidget::yt5(qreal x)
{
    return qPow(qExp(1), 2 * x - 1) - 2 * qPow(qExp(1), x) + qExp(1) - 1;
}
Пример #14
0
/*!
   Draw the rose

   \param painter Painter
   \param palette Palette
   \param center Center of the rose
   \param radius Radius of the rose
   \param north Position pointing to north
   \param width Width of the rose
   \param numThorns Number of thorns
   \param numThornLevels Number of thorn levels
   \param shrinkFactor Factor to shrink the thorns with each level
*/
void QwtSimpleCompassRose::drawRose(
    QPainter *painter,
    const QPalette &palette,
    const QPointF &center, double radius, double north, double width,
    int numThorns, int numThornLevels, double shrinkFactor )
{
    if ( numThorns < 4 )
        numThorns = 4;

    if ( numThorns % 4 )
        numThorns += 4 - numThorns % 4;

    if ( numThornLevels <= 0 )
        numThornLevels = numThorns / 4;

    if ( shrinkFactor >= 1.0 )
        shrinkFactor = 1.0;

    if ( shrinkFactor <= 0.5 )
        shrinkFactor = 0.5;

    painter->save();

    painter->setPen( Qt::NoPen );

    for ( int j = 1; j <= numThornLevels; j++ )
    {
        double step =  qPow( 2.0, j ) * M_PI / numThorns;
        if ( step > M_PI_2 )
            break;

        double r = radius;
        for ( int k = 0; k < 3; k++ )
        {
            if ( j + k < numThornLevels )
                r *= shrinkFactor;
        }

        double leafWidth = r * width;
        if ( 2.0 * M_PI / step > 32 )
            leafWidth = 16;

        const double origin = north / 180.0 * M_PI;
        for ( double angle = origin;
            angle < 2.0 * M_PI + origin; angle += step )
        {
            const QPointF p = qwtPolar2Pos( center, r, angle );
            const QPointF p1 = qwtPolar2Pos( center, leafWidth, angle + M_PI_2 );
            const QPointF p2 = qwtPolar2Pos( center, leafWidth, angle - M_PI_2 );
            const QPointF p3 = qwtPolar2Pos( center, r, angle + step / 2.0 );
            const QPointF p4 = qwtPolar2Pos( center, r, angle - step / 2.0 );

            QPainterPath darkPath;
            darkPath.moveTo( center );
            darkPath.lineTo( p );
            darkPath.lineTo( qwtIntersection( center, p3, p1, p ) );

            painter->setBrush( palette.brush( QPalette::Dark ) );
            painter->drawPath( darkPath );

            QPainterPath lightPath;
            lightPath.moveTo( center );
            lightPath.lineTo( p );
            lightPath.lineTo( qwtIntersection( center, p4, p2, p ) );

            painter->setBrush( palette.brush( QPalette::Light ) );
            painter->drawPath( lightPath );
        }
    }
    painter->restore();
}
Пример #15
0
void FeaturesCalculation::calculateTextureParameter(PARAMETR param)
{
    float qrt = 0, fabs = 0, thigmaSqr = 0, U = 0;
    for(int k = 0; k < seedVect.length(); k++)
    {
        for(int i=0; i< seedVect[k].GLCM.rows; i++)
            for(int j=0; j< seedVect[k].GLCM.cols; j++)
            {

                if(param == DISSIMILARITY)
                {
                    qrt = qPow(i-j,2);
                    fabs = qSqrt(qrt);
                    seedVect[k].dissimilarity += fabs*seedVect[k].GLCM.at<uchar>(i,j);
                }

                if(param == ENERGY)
                {
                    seedVect[k].energy += qPow(seedVect[k].GLCM.at<uchar>(i,j),2);
                }

                if(param == ENTROPY)
                {
                    if (seedVect[k].GLCM.at<uchar>(i,j) != 0)
                    {
//                        float ln = -qLn(seedVect[k].GLCM.at<uchar>(i,j));
                        seedVect[k].entropy += -qLn(seedVect[k].GLCM.at<uchar>(i,j)) * seedVect[k].GLCM.at<uchar>(i,j);
                    }
//                    printf("ln = %f, char =%d entropy = %f\n", ln, seedVect[k].GLCM.at<uchar>(i,j), seedVect[k].entropy);
                }

                if(param == HOMOGENEITY)
                {
                    qrt = qPow(i-j,2);
                    if(qrt != 1)
                        seedVect[k].homogeneity += (1/(1-qPow(i-j,2)))*seedVect[k].GLCM.at<uchar>(i,j);
                }

                if(param == CONTRAST)
                {
                    int pixel = seedVect[k].GLCM.at<uchar>(i,j);
                    float dividing = pixel;
                    float qrt = qPow(i-j, 2);
                    float contr = qrt * dividing;

                    seedVect[k].contrast += contr;
                }

                if(param == CORRELATION)
                {
                    calculateUandThigma(k, U, thigmaSqr);
                    seedVect[k].correlation += seedVect[k].GLCM.at<uchar>(i,j)*(i-U)*(j-U) / thigmaSqr;
                }



            }



        if(param == DISSIMILARITY)
            seedVect[k].dissimilarity = seedVect[k].dissimilarity / (seedVect[k].countOfPairs);

        if(param == HOMOGENEITY)
            seedVect[k].homogeneity = seedVect[k].homogeneity / (seedVect[k].countOfPairs);

        if(param == CONTRAST)
            seedVect[k].contrast = seedVect[k].contrast/(seedVect[k].countOfPairs);

        if(param == ENERGY)
            seedVect[k].energy = seedVect[k].energy / (seedVect[k].countOfPairs);

        if(param == ENTROPY)
            seedVect[k].entropy = seedVect[k].entropy / (seedVect[k].countOfPairs);

        if(param == CORRELATION)
            seedVect[k].correlation = seedVect[k].correlation / (seedVect[k].countOfPairs);





    }
}
Пример #16
0
QImage EdgeDetection::gradientMagnitudeImage(QImage *image)
{
    QImage new_image(image->size(), QImage::Format_ARGB32_Premultiplied);
//    QImage orient_image(image->size(), QImage::Format_ARGB32_Premultiplied);

    QList<QPair<QPoint, QPair<int, int> > > x_y_struct;
    x_y_struct.append( qMakePair(QPoint(-1,-1), QPair<int,int>(-1, 1) ));
    x_y_struct.append( qMakePair(QPoint(-1,0), QPair<int,int>(-2, 0) ));
    x_y_struct.append( qMakePair(QPoint(-1,1), QPair<int,int>(-1,-1) ));
    x_y_struct.append( qMakePair(QPoint(0,-1), QPair<int,int>(0,2) ));
    x_y_struct.append( qMakePair(QPoint(0,0), QPair<int,int>(0,0) ));
    x_y_struct.append( qMakePair(QPoint(0,1), QPair<int,int>(0,-2) ));
    x_y_struct.append( qMakePair(QPoint(1,-1), QPair<int,int>(1,1) ));
    x_y_struct.append( qMakePair(QPoint(1,0), QPair<int,int>(2,0) ));
    x_y_struct.append( qMakePair(QPoint(1,1), QPair<int,int>(1, -1) ));

//    QList<QPair<QPoint, qreal> > orientations;
//    qreal orien_min = 1000;
//    qreal orien_max = 0;

//    int threshold = QInputDialog::getInteger(0, "Threshold", "Threshold value:", -1, -1, 255);

    for( int y=0; y < image->height(); y++ ) {
        for( int x=0; x < image->width(); x++ ) {
            QPoint point(x,y);
            int x_sum = 0;
            int x_rsum = 0;
            int x_gsum = 0;
            int x_bsum = 0;
            int y_sum = 0;
            int y_rsum = 0;
            int y_gsum = 0;
            int y_bsum = 0;
            //Perform Convolution on X
            for (int i=0; i < x_y_struct.size(); i++) {
                QPoint offset = x_y_struct.at(i).first;
                QPair<int,int> multiplier = x_y_struct.at(i).second;
                //Only convolve real pixels
                int pixel_x = offset.x() + x;
                int pixel_y = offset.y() + y;
                QRgb color;
                if ( pixel_x < 0 ||
                     pixel_x >= image->width() ||
                     pixel_y < 0 ||
                     pixel_y >= image->height() ) {
                    color = qRgb(128, 128, 128);
                } else {
                    color = image->pixel(QPoint(pixel_x, pixel_y));
                }

                int gray_val = qGray(color);
                x_sum += gray_val * multiplier.first;
                x_rsum += qRed(color) * multiplier.first;
                x_gsum += qGreen(color) * multiplier.first;
                x_bsum += qBlue(color) * multiplier.first;
                y_sum += gray_val * multiplier.second;
                y_rsum += qRed(color) * multiplier.second;
                y_gsum += qGreen(color) * multiplier.second;
                y_bsum += qBlue(color) * multiplier.second;
            }


            //Gradient
            qreal gradient = qSqrt(qPow(x_sum / 8, 2) + qPow(y_sum / 8, 2));
            qreal r_gradient = qSqrt(qPow(x_rsum / 8, 2) + qPow(y_rsum / 8, 2));
            qreal g_gradient = qSqrt(qPow(x_gsum / 8, 2) + qPow(y_gsum / 8, 2));
            qreal b_gradient = qSqrt(qPow(x_bsum / 8, 2) + qPow(y_bsum / 8, 2));

            //Orientation
//            qreal orientation = qAtan2(y_sum, x_sum);
//            if ( orientation < orien_min )
//                orien_min = orientation;

//            if ( orientation > orien_max )
//                orien_max = orientation;
//            orientations.append(qMakePair(point, orientation));

            //Threshold
//            QRgb val;
//            if ( threshold < 0 ) {
//                val = qRgb(gradient, gradient, gradient);
//            } else if ( gradient > threshold ) {
//                val = qRgb(255,255,255);
//            } else
//                val = qRgb(0,0,0);
//            new_image.setPixel(point, val);

            new_image.setPixel(point, qRgb(r_gradient, g_gradient, b_gradient));
        }
    }

//    for( int i=0; i < orientations.size(); i++ ) {
//        QPair<QPoint, qreal> o_pair = orientations.at(i);
//        qreal normal = Utility::rangeConvert(orien_max, orien_min, 255, 0, o_pair.second);
//        orient_image.setPixel(o_pair.first, qRgb(normal, normal, normal));
//    }


    return new_image;
}
Пример #17
0
/*!
   \brief Calculate minor/medium ticks for major ticks

   \param majorTicks Major ticks
   \param maxMinorSteps Maximum number of minor steps
   \param stepSize Step size
   \param minorTicks Array to be filled with the calculated minor ticks
   \param mediumTicks Array to be filled with the calculated medium ticks
*/
void QwtLogScaleEngine::buildMinorTicks(
    const QList<double> &majorTicks,
    int maxMinorSteps, double stepSize,
    QList<double> &minorTicks,
    QList<double> &mediumTicks ) const
{
    const double logBase = base();

    if ( stepSize < 1.1 )          // major step width is one base
    {
        double minStep = divideInterval( stepSize, maxMinorSteps + 1 );
        if ( minStep == 0.0 )
            return;

        const int numSteps = qRound( stepSize / minStep );

        int mediumTickIndex = -1;
        if ( ( numSteps > 2 ) && ( numSteps % 2 == 0 ) )
            mediumTickIndex = numSteps / 2;

        for ( int i = 0; i < majorTicks.count() - 1; i++ )
        {
            const double v = majorTicks[i];
            const double s = logBase / numSteps;

            if ( s >= 1.0 )
            {
                if ( !qFuzzyCompare( s, 1.0 ) )
                    minorTicks += v * s;

                for ( int j = 2; j < numSteps; j++ )
                {
                    minorTicks += v * j * s;
                }
            }
            else
            {
                for ( int j = 1; j < numSteps; j++ )
                {
                    const double tick = v + j * v * ( logBase - 1 ) / numSteps;
                    if ( j == mediumTickIndex )
                        mediumTicks += tick;
                    else
                        minorTicks += tick;
                }
            }
        }
    }
    else
    {
        double minStep = divideInterval( stepSize, maxMinorSteps );
        if ( minStep == 0.0 )
            return;

        if ( minStep < 1.0 )
            minStep = 1.0;

        // # subticks per interval
        int numTicks = qRound( stepSize / minStep ) - 1;

        // Do the minor steps fit into the interval?
        if ( qwtFuzzyCompare( ( numTicks +  1 ) * minStep,
            stepSize, stepSize ) > 0 )
        {
            numTicks = 0;
        }

        if ( numTicks < 1 )
            return;

        int mediumTickIndex = -1;
        if ( ( numTicks > 2 ) && ( numTicks % 2 ) )
            mediumTickIndex = numTicks / 2;

        // substep factor = base^substeps
        const qreal minFactor = qMax( qPow( logBase, minStep ), qreal( logBase ) );

        for ( int i = 0; i < majorTicks.count(); i++ )
        {
            double tick = majorTicks[i];
            for ( int j = 0; j < numTicks; j++ )
            {
                tick *= minFactor;

                if ( j == mediumTickIndex )
                    mediumTicks += tick;
                else
                    minorTicks += tick;
            }
        }
    }
}
Пример #18
0
QWidget *WalkmeshManager::buildCameraPage()
{
	QWidget *ret = new QWidget(this);

	ListWidget *listWidget = new ListWidget(ret);
	listWidget->addAction(ListWidget::Add, tr("Ajouter caméra"), this, SLOT(addCamera()));
	listWidget->addAction(ListWidget::Rem, tr("Supprimer caméra"), this, SLOT(removeCamera()));

	caToolbar = listWidget->toolBar();
	camList = listWidget->listWidget();

	caVectorXEdit = new VertexWidget(ret);
	caVectorYEdit = new VertexWidget(ret);
	caVectorZEdit = new VertexWidget(ret);

	caSpaceXEdit = new QDoubleSpinBox(ret);
	qreal maxInt = qPow(2,31);
	caSpaceXEdit->setRange(-maxInt, maxInt);
	caSpaceXEdit->setDecimals(0);
	caSpaceYEdit = new QDoubleSpinBox(ret);
	caSpaceYEdit->setRange(-maxInt, maxInt);
	caSpaceYEdit->setDecimals(0);
	caSpaceZEdit = new QDoubleSpinBox(ret);
	caSpaceZEdit->setRange(-maxInt, maxInt);
	caSpaceZEdit->setDecimals(0);

	caZoomEdit = new QSpinBox(ret);
	caZoomEdit->setRange(-32768, 32767);

	QGridLayout *caLayout = new QGridLayout(ret);
	caLayout->addWidget(listWidget, 0, 0, 8, 1);
	caLayout->addWidget(new QLabel(tr("Distance (zoom) :")), 0, 1, 1, 3);
	caLayout->addWidget(caZoomEdit, 0, 4, 1, 2);
	caLayout->addWidget(new QLabel(tr("Axes de la caméra :")), 1, 1, 1, 6);
	caLayout->addWidget(caVectorXEdit, 2, 1, 1, 6);
	caLayout->addWidget(caVectorYEdit, 3, 1, 1, 6);
	caLayout->addWidget(caVectorZEdit, 4, 1, 1, 6);
	caLayout->addWidget(new QLabel(tr("Position de la caméra :")), 5, 1, 1, 6);
	caLayout->addWidget(new QLabel(tr("X")), 6, 1);
	caLayout->addWidget(caSpaceXEdit, 6, 2);
	caLayout->addWidget(new QLabel(tr("Y")), 6, 3);
	caLayout->addWidget(caSpaceYEdit, 6, 4);
	caLayout->addWidget(new QLabel(tr("Z")), 6, 5);
	caLayout->addWidget(caSpaceZEdit, 6, 6);
	caLayout->setRowStretch(7, 1);
	caLayout->setColumnStretch(2, 1);
	caLayout->setColumnStretch(4, 1);
	caLayout->setColumnStretch(6, 1);

	connect(camList, SIGNAL(currentRowChanged(int)), SLOT(setCurrentCamera(int)));

	connect(caVectorXEdit, SIGNAL(valuesChanged(Vertex_s)), SLOT(editCaVector(Vertex_s)));
	connect(caVectorYEdit, SIGNAL(valuesChanged(Vertex_s)), SLOT(editCaVector(Vertex_s)));
	connect(caVectorZEdit, SIGNAL(valuesChanged(Vertex_s)), SLOT(editCaVector(Vertex_s)));

	connect(caSpaceXEdit, SIGNAL(valueChanged(double)), SLOT(editCaPos(double)));
	connect(caSpaceYEdit, SIGNAL(valueChanged(double)), SLOT(editCaPos(double)));
	connect(caSpaceZEdit, SIGNAL(valueChanged(double)), SLOT(editCaPos(double)));

	connect(caZoomEdit, SIGNAL(valueChanged(int)), SLOT(editCaZoom(int)));

	return ret;
}
Пример #19
0
/*!
    Align and divide an interval

   \param maxNumSteps Max. number of steps
   \param x1 First limit of the interval (In/Out)
   \param x2 Second limit of the interval (In/Out)
   \param stepSize Step size (Out)

   \sa QwtScaleEngine::setAttribute()
*/
void QwtLogScaleEngine::autoScale( int maxNumSteps,
    double &x1, double &x2, double &stepSize ) const
{
    if ( x1 > x2 )
        qSwap( x1, x2 );

    const double logBase = base();

    QwtInterval interval( x1 / qPow( logBase, lowerMargin() ),
        x2 * qPow( logBase, upperMargin() ) );

    if ( interval.maxValue() / interval.minValue() < logBase )
    {
        // scale width is less than one step -> try to build a linear scale

        QwtLinearScaleEngine linearScaler;
        linearScaler.setAttributes( attributes() );
        linearScaler.setReference( reference() );
        linearScaler.setMargins( lowerMargin(), upperMargin() );

        linearScaler.autoScale( maxNumSteps, x1, x2, stepSize );

        QwtInterval linearInterval = QwtInterval( x1, x2 ).normalized();
        linearInterval = linearInterval.limited( LOG_MIN, LOG_MAX );

        if ( linearInterval.maxValue() / linearInterval.minValue() < logBase )
        {
            // the aligned scale is still less than one step

#if 1
            // this code doesn't make any sense, but for compatibility
            // reasons we keep it until 6.2. But it will be ignored
            // in divideScale

            if ( stepSize < 0.0 )
                stepSize = -qwtLog( logBase, qAbs( stepSize ) );
            else
                stepSize = qwtLog( logBase, stepSize );
#endif

            return;
        }
    }

    double logRef = 1.0;
    if ( reference() > LOG_MIN / 2 )
        logRef = qMin( reference(), LOG_MAX / 2 );

    if ( testAttribute( QwtScaleEngine::Symmetric ) )
    {
        const double delta = qMax( interval.maxValue() / logRef,
            logRef / interval.minValue() );
        interval.setInterval( logRef / delta, logRef * delta );
    }

    if ( testAttribute( QwtScaleEngine::IncludeReference ) )
        interval = interval.extend( logRef );

    interval = interval.limited( LOG_MIN, LOG_MAX );

    if ( interval.width() == 0.0 )
        interval = buildInterval( interval.minValue() );

    stepSize = divideInterval( qwtLogInterval( logBase, interval ).width(),
        qMax( maxNumSteps, 1 ) );
    if ( stepSize < 1.0 )
        stepSize = 1.0;

    if ( !testAttribute( QwtScaleEngine::Floating ) )
        interval = align( interval, stepSize );

    x1 = interval.minValue();
    x2 = interval.maxValue();

    if ( testAttribute( QwtScaleEngine::Inverted ) )
    {
        qSwap( x1, x2 );
        stepSize = -stepSize;
    }
}
Пример #20
0
double QgsRasterChecker::tolerance( double val, int places )
{
  // float precision is about 7 decimal digits, double about 16
  // default places = 6
  return 1. * qPow( 10, qRound( log10( qAbs( val ) ) - places ) );
}
Пример #21
0
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    pressed = true;
    clicked_point = static_cast<QMouseEvent*>(event)->pos();

    if(skill && shot && pressed && CD)
    {
        b2Vec2 gravity;
        b2Vec2 speed = (*Bit)->Body->GetLinearVelocity();
        b2Vec2 gravity_center;
        b2Vec2 bodypos;
        float dist;
        switch(bird_count-1)
        {
            case 1:
                qDebug() << "red";
                skill = false;
                pressed = false;
            break;
            case 2:
                qDebug() << "yellow";
                (*Bit)->Body->SetLinearVelocity(b2Vec2(speed.x*10,speed.y*10));
                skill = false;
                pressed = false;
            break;
            case 3:
                qDebug() << "iron";
                (*Bit)->Body->SetLinearVelocity(b2Vec2(0,-300));
                skill = false;
                pressed = false;
            break;
            case 4:
                qDebug() << "black";
                gravity_center = (*Bit)->Body->GetPosition();
                for(it=WOOD.begin(); it!=WOOD.end(); ++it)
                {
                    bodypos = (*it)->Body->GetPosition();
                    dist = qSqrt(qPow(gravity_center.x-bodypos.x,2)+qPow(gravity_center.y-bodypos.y,2));
                    if(dist<=4)
                    {
                        gravity = b2Vec2(4000000/dist,4000000/dist);
                        (*it)->Body->ApplyForceToCenter(gravity, true);
                    }
                }
                for(it=PIG.begin(); it!=PIG.end(); ++it)
                {
                    bodypos = (*it)->Body->GetPosition();
                    dist = qSqrt(qPow(gravity_center.x-bodypos.x,2)+qPow(gravity_center.y-bodypos.y,2));
                    gravity = b2Vec2(800000/dist,800000/dist);
                    (*it)->Body->ApplyForceToCenter(gravity, true);
                }
                skill = false;
                pressed = false;
            break;
            case 5:
                qDebug() << "TA NUCLEAR";
                gravity_center = (*Bit)->Body->GetPosition();
                for(it=WOOD.begin(); it!=WOOD.end(); ++it)
                {
                    bodypos = (*it)->Body->GetPosition();
                    dist = qSqrt(qPow(gravity_center.x-bodypos.x,2)+qPow(gravity_center.y-bodypos.y,2));
                    gravity = b2Vec2(20000000000/dist,20000000000/dist);
                    (*it)->Body->ApplyForceToCenter(gravity, true);
                }
                for(it=PIG.begin(); it!=PIG.end(); ++it)
                {
                    bodypos = (*it)->Body->GetPosition();
                    dist = qSqrt(qPow(gravity_center.x-bodypos.x,2)+qPow(gravity_center.y-bodypos.y,2));
                    gravity = b2Vec2(20000000000/dist,20000000000/dist);
                    (*it)->Body->ApplyForceToCenter(gravity, true);
                }
                (*Bit)->Body->ApplyLinearImpulse(b2Vec2(400000,400000),gravity_center,true);
                skill = false;
                pressed = false;
            break;
            default:
                qDebug() << "nothing happens";
            break;
        }
    }
}
Пример #22
0
// Méthodes publiques
char * Page::getTextValue(char * T, WORD champ, genAmountType genVal)
{
    switch (champ)
    {
    case champ_velRange:
        if (genVal.ranges.byLo == genVal.ranges.byHi)
            sprintf(T, "%d", genVal.ranges.byLo);
        else
            sprintf(T, "%d-%d", genVal.ranges.byLo, genVal.ranges.byHi);
        break;
    case champ_keyRange:
        if (genVal.ranges.byLo == genVal.ranges.byHi)
            sprintf(T, "%s", Config::getInstance()->getKeyName(genVal.ranges.byLo).toStdString().c_str());
        else
            sprintf(T, "%s-%s", Config::getInstance()->getKeyName(genVal.ranges.byLo).toStdString().c_str(),
                    Config::getInstance()->getKeyName(genVal.ranges.byHi).toStdString().c_str());
        break;
    case champ_initialAttenuation: case champ_pan: case champ_initialFilterQ:
    case champ_modLfoToVolume:
    case champ_sustainVolEnv: case champ_sustainModEnv:
    case champ_chorusEffectsSend: case champ_reverbEffectsSend:
        sprintf(T, "%.1f", (double)genVal.shAmount/10);
        break;

    case champ_keynum: case champ_overridingRootKey:
        sprintf(T, "%s", Config::getInstance()->getKeyName(genVal.wAmount).toStdString().c_str());
        break;

    case champ_sampleModes: case champ_exclusiveClass: case champ_velocity:
        sprintf(T,"%d", genVal.wAmount);
        break;

    case champ_scaleTuning: case champ_coarseTune: case champ_fineTune:
    case champ_modLfoToFilterFc: case champ_modEnvToFilterFc:
    case champ_modEnvToPitch: case champ_modLfoToPitch: case champ_vibLfoToPitch:
    case champ_keynumToModEnvHold: case champ_keynumToVolEnvHold:
    case champ_keynumToModEnvDecay: case champ_keynumToVolEnvDecay:
    case champ_startAddrsOffset: case champ_startAddrsCoarseOffset:
    case champ_startloopAddrsOffset: case champ_startloopAddrsCoarseOffset:
    case champ_endAddrsOffset: case champ_endAddrsCoarseOffset:
    case champ_endloopAddrsOffset: case champ_endloopAddrsCoarseOffset:
        sprintf(T,"%d", genVal.shAmount);
        break;

    case champ_initialFilterFc:
        if (m_typePage == PAGE_PRST)
            sprintf(T,"%.3f", qPow(2., (double)genVal.shAmount/1200));
        else
            sprintf(T,"%.0f", qPow(2., (double)genVal.shAmount/1200)*8.176);
        break;

    case champ_freqModLFO: case champ_freqVibLFO:
        if (m_typePage == PAGE_PRST)
            sprintf(T,"%.3f", qPow(2., (double)genVal.shAmount/1200));
        else
            sprintf(T,"%.3f", qPow(2., (double)genVal.shAmount/1200)*8.176);
        break;

    case champ_delayModEnv: case champ_attackModEnv: case champ_holdModEnv: case champ_decayModEnv: case champ_releaseModEnv:
    case champ_delayVolEnv: case champ_attackVolEnv: case champ_holdVolEnv: case champ_decayVolEnv: case champ_releaseVolEnv:
    case champ_delayModLFO: case champ_delayVibLFO:
        sprintf(T,"%.3f", qPow(2., (double)genVal.shAmount/1200)); break;

    case champ_sfModDestOper:
        sprintf(T,"%d", genVal.wAmount);
        break;
    case champ_sfModTransOper:
        switch (genVal.wAmount)
        {
        case 2: strcpy(T, trUtf8(", valeur absolue").toStdString().c_str()); break;
        default: T[0] = '\0';
        }
        break;
    case champ_modAmount:
        sprintf(T,"%d", genVal.shAmount);
        break;
    case champ_indexMod:
        sprintf(T,"%d", genVal.wAmount+1);
        break;
    default: break;
    }
    return T;
}
double BodySurfaceAreaFormula::compute(int patientsHeightInCm, int patientsWeightInKg)
{
    return 71.84 * pow(patientsHeightInCm, 0.725) * qPow(patientsWeightInKg, 0.425);
}
Пример #24
0
//*************------------SLOTS------------************
void WindowGUI::toBinImg(){
    //@TODO consider strategy pattern for binarization and making histogram
    //FOR NOW - create grayscale img from origin, make simple histogram, use
    //simplified otsu method and show img, everything in one method :(

    binarizeBut->setEnabled( false );
    clusterBut->setEnabled( true );

    qDebug() << "toBinImg slot";
    
   //copy img, change to grayscale and make histogram, consider 8bit format
    QImage grayImg { originImg.convertToFormat( QImage::Format_RGB32 ) };
    if ( grayImg.isNull() ){
        QMessageBox::information( this, tr("Projective Clustering"),
                                    tr("cannot load"));
        return;
    }
    int gray{}, width{ grayImg.width() }, height { grayImg.height() };
    long histogram[256] = {};
    for ( int i = 0; i < width; ++i){
        for ( int j = 0; j < height; ++j ){
            gray = qGray( grayImg.pixel( i, j ) ) ;
            histogram[ gray ]++;
            //grayImg.setPixel( i, j, qRgb( gray, gray, gray ) );
        }
    }
    //simple otsu method - use created grayscale histogram to compute threshold
    //theoretically need total pixels and histogram, return threshold
    double sum{}, sumB{}, wB{}, wF{}, mB{}, mF{}, max{}, between{},
           threshold1{}, threshold2{}, results{}; 
    long total{ ( width * height ) };
    for ( int i = 1; i < 256; ++i )
        sum += i * histogram[i];
    for ( int i = 0; i < 256; ++i) {
        wB += histogram[i];
        if (wB == 0)
            continue;
            wF = total - wB;
        if (wF == 0)
            break;
        sumB += i * histogram[i];
        mB = sumB / wB;
        mF = (sum - sumB) / wF;
        between = wB * wF * qPow(mB - mF, 2);
        if ( between >= max ) {
            threshold1 = i;
            if ( between > max ) {
                threshold2 = i;
            }
            max = between;            
        }
    }
    results = ( threshold1 + threshold2 ) / 2.0;

    //now change all pixel below results to white and above to black
    for ( int i = 0; i < width; ++i ){
        for ( int j = 0; j < height; ++j ){
            double avg = static_cast<double>( qGray( originImg.pixel( i, j ) ));
            if( results < avg )
                grayImg.setPixel( i, j, qRgb( 0, 0, 0 ) );
            else
                grayImg.setPixel( i, j, qRgb( 255, 255, 255 ) );
        }
    }
    imgLab->setPixmap( QPixmap::fromImage( grayImg ) );
    binImg = std::move( grayImg );
}
float voiceFromDb(float Db)
{
	return (qPow(10.0,0.05*(Db)));
}
Пример #26
0
// Flood fill
// ----- http://lodev.org/cgtutor/floodfill.html
void BitmapImage::floodFill(BitmapImage* targetImage,
                            QRect cameraRect,
                            QPoint point,
                            QRgb newColor,
                            int tolerance)
{
    // If the point we are supposed to fill is outside the image and camera bounds, do nothing
    if(!cameraRect.united(targetImage->bounds()).contains(point))
    {
        return;
    }

    // Square tolerance for use with compareColor
    tolerance = static_cast<int>(qPow(tolerance, 2));

    QRgb oldColor = targetImage->pixel(point);
    oldColor = qRgba(qRed(oldColor), qGreen(oldColor), qBlue(oldColor), qAlpha(oldColor));

    // Preparations
    QList<QPoint> queue; // queue all the pixels of the filled area (as they are found)

    BitmapImage* replaceImage = nullptr;
    QPoint tempPoint;
    QRgb newPlacedColor = 0;
    QScopedPointer< QHash<QRgb, bool> > cache(new QHash<QRgb, bool>());

    int xTemp = 0;
    bool spanLeft = false;
    bool spanRight = false;

    // Extend to size of Camera
    targetImage->extend(cameraRect);
    replaceImage = new BitmapImage(cameraRect, Qt::transparent);

    queue.append(point);
    // Preparations END

    while (!queue.empty())
    {
        tempPoint = queue.takeFirst();

        point.setX(tempPoint.x());
        point.setY(tempPoint.y());

        xTemp = point.x();

        newPlacedColor = replaceImage->constScanLine(xTemp, point.y());
        while (xTemp >= targetImage->mBounds.left() &&
               compareColor(targetImage->constScanLine(xTemp, point.y()), oldColor, tolerance, cache.data())) xTemp--;
        xTemp++;

        spanLeft = spanRight = false;
        while (xTemp <= targetImage->mBounds.right() &&
               compareColor(targetImage->constScanLine(xTemp, point.y()), oldColor, tolerance, cache.data()) &&
               newPlacedColor != newColor)
        {

            // Set pixel color
            replaceImage->scanLine(xTemp, point.y(), newColor);

            if (!spanLeft && (point.y() > targetImage->mBounds.top()) &&
                compareColor(targetImage->constScanLine(xTemp, point.y() - 1), oldColor, tolerance, cache.data())) {
                queue.append(QPoint(xTemp, point.y() - 1));
                spanLeft = true;
            }
            else if (spanLeft && (point.y() > targetImage->mBounds.top()) &&
                     !compareColor(targetImage->constScanLine(xTemp, point.y() - 1), oldColor, tolerance, cache.data())) {
                spanLeft = false;
            }

            if (!spanRight && point.y() < targetImage->mBounds.bottom() &&
                compareColor(targetImage->constScanLine(xTemp, point.y() + 1), oldColor, tolerance, cache.data())) {
                queue.append(QPoint(xTemp, point.y() + 1));
                spanRight = true;

            }
            else if (spanRight && point.y() < targetImage->mBounds.bottom() &&
                     !compareColor(targetImage->constScanLine(xTemp, point.y() + 1), oldColor, tolerance, cache.data())) {
                spanRight = false;
            }

            Q_ASSERT(queue.count() < (targetImage->mBounds.width() * targetImage->mBounds.height()));
            xTemp++;
        }
    }

    targetImage->paste(replaceImage);
    targetImage->modification();
    delete replaceImage;
}
Пример #27
0
qreal Curve::calcXDerivative(qreal t)
{
	return -2 * t / qPow(t * t - 1, 2.);
}
Пример #28
0
void FeaturesCalculation::calculateSomeGeometryParam(PARAMETR param)
{
    int i = 0, oldArea, oldLuma,  oldPixel;
    int len = seedVect.length();
    Mat channel[3], YCRImage;
    cvtColor(firstImg, YCRImage, COLOR_BGR2YCrCb);
    split(YCRImage, channel);

    double *m11 = new double[len];
    double *m02 = new double[len];
    double *m20 = new double[len];

    for(int i =0; i < len; i++)
    {
        m11[i] = 0;
        m02[i] = 0;
        m20[i] = 0;
    }


    for( int y = 0; y < srcImg.rows; y++ )
       {
            for( int x = 0; x < srcImg.cols; x++ )
            {
                if(!(srcImg.at<Vec3b>(y,x)[0] == 0 &&
                        srcImg.at<Vec3b>(y,x)[1] == 0 &&
                        srcImg.at<Vec3b>(y,x)[2] == 0))
                {
                    i = 0;
                    for(Seed s: seedVect)
                    {

                        if(s.GetColor().val[0] == srcImg.at<Vec3b>(y,x)[0] &&
                           s.GetColor().val[1] == srcImg.at<Vec3b>(y,x)[1] &&
                           s.GetColor().val[2] == srcImg.at<Vec3b>(y,x)[2])
                        {
                            if(param == AREA)
                            {
                                oldArea = s.GetArea();
                                seedVect[i].SetArea(oldArea+1);
                                break;
                            }
                            if(param == LUMA)
                            {
                                oldLuma = s.GetLuma();
                                int l = channel[0].at<uchar>(y, x);
                                seedVect[i].SetLuma(oldLuma + l);
                                oldPixel = s.GetCountOfPixels();
                                seedVect[i].SetCountOfPixels(oldPixel+1);
                                break;
                            }
                            if(param == MATEXP)
                            {
                                seedVect[i].countOfPixelsOnLevel[channel[0].at<uchar>(y,x)]++;
                            }
                            if(param == MASSCENTRE)
                            {
                                seedVect[i].centerMass.x += x ;
                                seedVect[i].centerMass.y += y ;
                            }
                            if(param == ELONGATION)
                            {
                                m11[i] += (x - seedVect[i].centerMass.x)*(y - seedVect[i].centerMass.y);
                                m02[i] += qPow((y - seedVect[i].centerMass.y), 2);
                                m20[i] += qPow((x - seedVect[i].centerMass.x), 2);
                            }
                        }
                        i++;
                    }
                }
            }
       }
    if(param == LUMA)
    {
        float luma = 0;
        for(int k = 0; k < seedVect.length(); k++)
        {
            luma = seedVect[k].GetLuma() / seedVect[k].GetCountOfPixels();
            seedVect[k].SetLuma(luma);
            luma = 0;
        }
    }
    if(param == MATEXP)
    {
        for(int index = 0; index < seedVect.length(); index++)
        {
            for(int k = 0; k < 256; k++)
            {
                seedVect[index].matExpect += k * seedVect[index].countOfPixelsOnLevel[k] / seedVect[index].GetArea();
            }
        }
    }
    if(param == MASSCENTRE)
    {
        for(int index = 0; index < seedVect.length(); index++)
        {
            seedVect[index].centerMass.x /= seedVect[index].GetArea();
            seedVect[index].centerMass.y /= seedVect[index].GetArea();
        }
    }
    if(param == ELONGATION)
    {
        double m1=0, m2=0;
        for(int index = 0; index < seedVect.length(); index++)
        {
            m1 = (m20[index] + m02[index] + qSqrt((m20[index] - m02[index])*(m20[index] - m02[index]) + 4*m11[index]*m11[index]));
            m2 = (m20[index] + m02[index] - qSqrt((m20[index] - m02[index])*(m20[index] - m02[index]) + 4*m11[index]*m11[index]));
//            cout << "m1 = " << m1 << "m2 = " << m2 << "\n";
            seedVect[index].elongation = m1 / m2;
        }
    }

}
Пример #29
0
/*---------------------------------------------------------------------------
* Statistik berechnen
*---------------------------------------------------------------------------*/
void DtaFieldStatistics::calcStatistics( DataMap::const_iterator iteratorStart,
                                    DataMap::const_iterator iteratorEnd)
{
   // locale Variablen
   DataMap::const_iterator iterator = iteratorStart;
   quint32 lastTS = 0;
   bool firstDataset = true; // erster Datansatz in Bearbeitung
   QHash<QString, QMap<qreal,quint32> > analogValueMap; // Liste mit Werten zur Ermittlung des Median und der Standardabweichung
   QHash<QString,quint32> digitalLastTransition; // Zeitpunkt des letzten Zustandswechsels
   QHash<QString,quint32> digitalAvgOnCount;
   QHash<QString,quint32> digitalAvgOffCount;

   do
   {
      quint32 ts = iterator.key();
      DataFieldValues data = iterator.value();

      if(firstDataset)
      {
         // Initialisierung
         m_dataStart = ts;
         m_datasets = 0;
         m_missingSum = m_missingCount = 0;
         m_analogFields.clear();
         m_analogStaticFields.clear();
         m_analogValues.clear();
         m_digitalFields.clear();
         m_digitalStaticFields.clear();
         m_digitalValues.clear();

         // Feldliste durchlaufen und analog/digitale Felder suchen
         for( int i=0; i<data.size(); ++i)
         {
            QString field = DataFile::fieldName(i);
            qreal value = data[i];
            const DataFieldInfo info = DataFile::fieldInfo(i);

            if(info.analog)
            {
               // analoges Feld: min, max, Durchschnitt, Median, Standardabweichung
               m_analogFields << field;
               m_analogValues.insert( field, QVarLengthArray<qreal>(aStdev+1));
               m_analogValues[field][aMin]    = value;
               m_analogValues[field][aMax]    = value;
               m_analogValues[field][aAvg]    = 0.0;
               m_analogValues[field][aMedian] = 0.0;
               m_analogValues[field][aStdev]  = 0.0;
               analogValueMap.insert( field, QMap<qreal,quint32>());
            }
            else
            {
               // digitale Felder: Anzahl von Impulsen, Zeit (in)aktive, Durschnittliche Laufzeit
               m_digitalFields << field;
               m_digitalValues.insert( field, QVarLengthArray<quint32>(dOff+1));
               m_digitalValues[field][dActOn] = 0;
               m_digitalValues[field][dActOff] = 0;
               m_digitalValues[field][dLast] = qRound(value);
               m_digitalValues[field][dMinOn] = 0;
               m_digitalValues[field][dMaxOn] = 0;
               m_digitalValues[field][dAvgOn] = 0;
               m_digitalValues[field][dMinOff] = 0;
               m_digitalValues[field][dMaxOff] = 0;
               m_digitalValues[field][dAvgOff] = 0;
               m_digitalValues[field][dOn] = 0;
               m_digitalValues[field][dOff] = 0;
               digitalLastTransition.insert( field, 0);
               digitalAvgOnCount.insert( field, 0);
               digitalAvgOffCount.insert( field, 0);
            }
         } // for i (Felder)

         firstDataset = false;
      }
      else // !firstDataset
      {
         // Luecken suchen
         bool missingFound = false;
         if(ts-lastTS > MISSING_DATA_GAP)
         {
            m_missingCount++;
            m_missingSum += ts - lastTS - 60;
            missingFound = true;
         }

         // analoge Signale bearbeiten
         for( int i=0; i<m_analogFields.size(); i++)
         {
            QString field = m_analogFields.at(i);
            qreal value = DataFile::fieldValueReal(data,field);
            if( value < m_analogValues[field][aMin])
               m_analogValues[field][aMin]=value;
            if( value > m_analogValues[field][aMax])
               m_analogValues[field][aMax]=value;
            m_analogValues[field][aAvg] += value * (ts-lastTS);
            if(analogValueMap[field].contains(value))
               analogValueMap[field][value] += ts-lastTS;
            else
               analogValueMap[field][value] = ts-lastTS;
         } // for analogFields

         // digitale Signale bearbeiten
         for( int i=0; i<m_digitalFields.size(); i++)
         {
            QString field = m_digitalFields.at(i);
            qint32 value = DataFile::fieldValueInt(data,field);

            if(missingFound)
               // Luecke entdeckt
               digitalLastTransition[field] = 0;

//            if(!missingFound)
//            {
               qint32 last = m_digitalValues[field][dLast];
               if(value == 1)
               {
                  if(last==0)
                  {
                     // Ende einer AUS-Phase
                     m_digitalValues[field][dActOff]++;
                     if(digitalLastTransition[field] > 0)
                     {
                        quint32 runtime = ts - digitalLastTransition[field];
                        if( (m_digitalValues[field][dMinOff]==0) ||
                            (runtime < m_digitalValues[field][dMinOff]))
                           m_digitalValues[field][dMinOff] = runtime;
                        if( (m_digitalValues[field][dMaxOff]==0) ||
                            (runtime > m_digitalValues[field][dMaxOff]))
                           m_digitalValues[field][dMaxOff] = runtime;
                        m_digitalValues[field][dAvgOff] += runtime;
                        digitalAvgOffCount[field]++;
                     }
                     digitalLastTransition[field] = ts;
                  }
                  // EIN-Phase haelt an
                  m_digitalValues[field][dOn] += ts - lastTS;
               }
               else
               {
                  if(last==1)
                  {
                     // Ende einer EIN-Phase
                     m_digitalValues[field][dActOn]++;
                     if(digitalLastTransition[field] > 0)
                     {
                        quint32 runtime = ts - digitalLastTransition[field];
                        if( (m_digitalValues[field][dMinOn]==0) ||
                            (runtime < m_digitalValues[field][dMinOn]))
                           m_digitalValues[field][dMinOn] = runtime;
                        if( (m_digitalValues[field][dMaxOn]==0) ||
                            (runtime > m_digitalValues[field][dMaxOn]))
                           m_digitalValues[field][dMaxOn] = runtime;
                        m_digitalValues[field][dAvgOn] += runtime;
                        digitalAvgOnCount[field]++;
                     }
                     digitalLastTransition[field] = ts;
                  }
                  // AUS-Phase haelt an
                  m_digitalValues[field][dOff] += ts - lastTS;
               } // if/else value==1/0
//            } // if !missingFound

            // letzten Wert Speichern
            m_digitalValues[field][dLast] = value;
         }

      } // if/else firstDataset

      // Ende der Daten merken
      m_dataEnd = ts;
      m_datasets++;

      // letzten Zeitstempel merken
      lastTS = ts;

      // naechster Datensatz
      iterator++;
   } while( iterator != iteratorEnd);

   // Nachbearbeitung analoge Signale
   for( int i=0; i<m_analogFields.size(); i++)
   {
      QString field = m_analogFields.at(i);

      // statische Signale aussortieren
      if( m_analogValues[field][aMin] == m_analogValues[field][aMax])
      {
         m_analogStaticFields << field;
         continue;
      }

      // Durchschnitt
      m_analogValues[field][aAvg] = m_analogValues[field][aAvg]/(m_dataEnd-m_dataStart);

      quint32 range = m_dataEnd - m_dataStart;
      quint32 sumTime = 0;
      bool medianFound = false;
      QMap<qreal,quint32>::const_iterator iterator = analogValueMap[field].begin();
      QMap<qreal,quint32>::const_iterator iteratorEnd = analogValueMap[field].end();
      qreal lastValue = iterator.value();
      do
      {
         // Median
         if( !medianFound && (sumTime==range/2) )
         {
            m_analogValues[field][aMedian] = (iterator.key() + lastValue)/2;
            medianFound = true;
         }
         sumTime += iterator.value();
         if( !medianFound && (sumTime > range/2) )
         {
            m_analogValues[field][aMedian] = iterator.key();
            medianFound = true;
         }
         lastValue = iterator.key();

         // Standardabweichung
         m_analogValues[field][aStdev] +=
               iterator.value() * qPow(iterator.key() - m_analogValues[field][aAvg], 2);

         // naechster Datenpunkt
         iterator++;
      } while( iterator != iteratorEnd);

      // Standardabweichung
      m_analogValues[field][aStdev] =
            qSqrt( m_analogValues[field][aStdev] / qreal(sumTime));
   } // for analogFields

   // Nachbearbeitung digitalen Signale
   for( int i=0; i<m_digitalFields.size(); i++)
   {
      QString field = m_digitalFields.at(i);
      if( (m_digitalValues[field][dActOn]==0) && (m_digitalValues[field][dActOff]==0))
      {
         m_digitalStaticFields << field;
         continue;
      }

      // Mittelwert
      m_digitalValues[field][dAvgOn] =
            qRound( qreal(m_digitalValues[field][dAvgOn]) / qreal(digitalAvgOnCount[field]));
      m_digitalValues[field][dAvgOff] =
            qRound( qreal(m_digitalValues[field][dAvgOff]) / qreal(digitalAvgOffCount[field]));

   } // for digitalFields

   // statische Signal aus Liste entfernen
   for( int i=0; i<m_analogStaticFields.size(); i++)
      m_analogFields.removeOne(m_analogStaticFields.at(i));
   for( int i=0; i<m_digitalStaticFields.size(); i++)
      m_digitalFields.removeOne(m_digitalStaticFields.at(i));

   // Felder sortieren
   m_analogFields.sort();
   m_analogStaticFields.sort();
   m_digitalFields.sort();
   m_digitalStaticFields.sort();
}
Пример #30
0
// compute the geomerty factors of the chart
static void
geom (QTAChartCore * core)
{
  qint64 price_width, keepbottom, keeptop;
  qreal chart_high, chart_low, chart_height_prc = 1.0,  max_volume = 0;
  int listsize, counter, i;

  // find the size of the bar list
  listsize = core->HLOC->size ();
  if (listsize == 0)
    return;

  // width
  core->chartwidth =
    core->chartrightmost - *core->excess_drag_width - core->chartleftmost;

  // height
  if (core->nsubcharts > 0)
  {
    chart_height_prc = 1 - (core->nsubcharts * 0.175);
    if (chart_height_prc < 0.45)
      chart_height_prc = 0.45;
  }

  core->charttopmost = core->title_height + core->chartframe;
  core->chartheight = core->height -
                      ((core->chartframe * 2) + core->title_height + core->bottomline_height);
  core->chartheight *= chart_height_prc;
  core->chartbottomost = core->charttopmost + core->chartheight;

  // compute the number of bars on the chart
  core->nbars_on_chart = core->chartwidth / (core->framewidth * 1.5);

  // initialize chart high and low
  chart_low = std::numeric_limits < qreal >::max ();
  chart_high = std::numeric_limits < qreal >::min ();

  counter = 0;
  do
  {
    i = counter + *core->startbar;
    chart_high = qMax (chart_high, core->HIGH[i]);
    chart_low = qMin (chart_low, core->LOW[i]);
    max_volume = qMax (max_volume, core->VOLUME[i]);
    counter++;
  }
  while ((counter < (core->nbars_on_chart + 2)) &&
         ((counter + *core->startbar) < listsize));

  if (!core->always_redraw)
  {
    if (core->max_high >= chart_high && core->min_low <= chart_low )
    {
      core->redraw = false;
      if (!core->recalc &&
          (chart_high * 1.1 > core->max_high) &&
          (chart_low * 0.8 < core->min_low))
        return;
    }
  }

  core->redraw = true;
  core->recalc = true;
  core->max_high = chart_high;
  core->min_low = chart_low;

  // compute the charttop and the chartbottom
  core->charttop = (qint64) (chart_high / core->points);
  core->chartbottom = (qint64) (chart_low / core->points);
  
  // compute the gridstep
  core->gridstep =
    qPow (10, qCeil (qLog10 (core->charttop - core->chartbottom) - 1));

  // recompute the charttop and the chartbottom (in cents or pips)
  keepbottom = core->chartbottom;
  keeptop = core->charttop;
  
  core->charttop = (keeptop / core->gridstep) * core->gridstep;
  if (core->charttop < keeptop)
    core->charttop += core->gridstep;
           
  core->chartbottom = (keepbottom / core->gridstep) * core->gridstep;
  if (core->chartbottom <= 0)
  {
    core->chartbottom = core->gridstep;
    while (core->chartbottom > keepbottom && core->chartbottom > 4)
      core->chartbottom /= 2;
    
    core->chartbottom = qPow (10, qCeil (qLog10 (core->chartbottom) - 1));
    core->chartbottom = qCeil (keepbottom / core->chartbottom) * core->chartbottom;  
  }
  
  // at least 4 grid lines  
  while ((((qint64) (chart_high / core->points) - core->chartbottom) / core->gridstep) < 4)
    core->gridstep /= 2;
  
  // no more than 15 lines
  while (((core->charttop - core->chartbottom) / core->gridstep) > 15)
    core->gridstep *= 2;
  
  
  while (((qreal) qAbs (core->charttop - keeptop) / (qreal) core->gridstep) >= 2)
    core->charttop -= core->gridstep;  
    
  while (((qreal) qAbs (keepbottom - core->chartbottom) / (qreal) core->gridstep) >= 2)
    core->chartbottom += core->gridstep;
  
    
  // compute the dots_per_point and the dots_per_traded_unit
  price_width = core->charttop - core->chartbottom;
  core->dots_per_point = core->chartheight / (qreal) price_width;
}