bool RingResampler::open(int inSampleRate, int outSampleRate)
{
	qDebug() << "RingResampler: open( " << inSampleRate << ", " << outSampleRate << " )";
	//
	paSampleRate  = outSampleRate;
	vacSampleRate = inSampleRate;
	if(vacSampleRate < paSampleRate)
		buffSize = qPow(2, 12 + ((int)(qLn(paSampleRate/vacSampleRate)/qLn(2.0f)) + 3));
	else if(vacSampleRate == paSampleRate)
		buffSize = MAX_DSP_BUFFER_SIZE*4;
	else
		buffSize = qPow(2, 12 + ((int)(qLn(vacSampleRate/paSampleRate)/qLn(2.0f)) + 3));

	if(!NUMBER_IS_2_POW_K(buffSize))
	{
		qWarning() << "RingResampler: open: incorrect buffer size = " << buffSize << " !";
		return (false);
	}
	resPaToVac->initialize(paSampleRate, vacSampleRate);
	resVacToPa->initialize(vacSampleRate, paSampleRate);
	pDataInputL->Resize(buffSize);
	pDataInputR->Resize(buffSize);
	pDataOutputL->Resize(buffSize);
	pDataOutputR->Resize(buffSize);
	pDataInputL->Clear();
	pDataInputR->Clear();
	pDataOutputL->Clear();
	pDataOutputR->Clear();
	qMemSet(pInDataL,  0, MAX_DSP_BUFFER_SIZE*sizeof(float));
	qMemSet(pInDataR,  0, MAX_DSP_BUFFER_SIZE*sizeof(float));
	qMemSet(pOutDataL, 0, MAX_DSP_BUFFER_SIZE*sizeof(float));
	qMemSet(pOutDataR, 0, MAX_DSP_BUFFER_SIZE*sizeof(float));
	isOpened = true;
	return (true);
}
Esempio n. 2
0
int TrackRecorder::fitZoomLevel(int width, int height) {
    if(m_points.size() < 2 || width < 1 || height < 1) {
        // One point track or zero size map
        return 20;
    }

    // Keep also current position in view
    qreal minLon = qMin(m_minLon, (qreal)m_currentPosition.longitude());
    qreal maxLon = qMax(m_maxLon, (qreal)m_currentPosition.longitude());
    qreal minLat = qMin(m_minLat, (qreal)m_currentPosition.latitude());
    qreal maxLat = qMax(m_maxLat, (qreal)m_currentPosition.latitude());

    qreal trackMinX = (minLon + 180) / 360;
    qreal trackMaxX = (maxLon + 180) / 360;
    qreal trackMinY = sqrt(1-qLn(minLat*M_PI/180 + 1/qCos(minLat*M_PI/180))/M_PI);
    qreal trackMaxY = sqrt(1-qLn(maxLat*M_PI/180 + 1/qCos(maxLat*M_PI/180))/M_PI);

    qreal coord, pixel;
    qreal trackAR = qAbs((trackMaxX - trackMinX) / (trackMaxY - trackMinY));
    qreal windowAR = (qreal)width/(qreal)height;
    if(trackAR > windowAR ) {
        // Width limits
        coord = qAbs(trackMaxX - trackMinX);
        pixel = width;
    } else {
        // height limits
        coord = qAbs(trackMaxY - trackMinY);
        pixel = height;
    }

    // log2(x) = ln(x)/ln(2)
    int z = qFloor(qLn(pixel/256.0 * 1.0/coord * qCos((m_minLat+m_maxLat)/2*M_PI/180))
                   / qLn(2)) + 1;
    return z;
}
Esempio n. 3
0
void Q3PlotAxis::generateAutoTicks()
{
    ticks_.clear();

    tickStep_ = (upper_ - lower_) / (double) (autoTickCount_ + 1e-10);
    qreal magnitudeFactor = qPow(10., qFloor(qLn(tickStep_) / qLn(10.)));
    qreal tickStepMantissa = tickStep_ / magnitudeFactor;
    if (tickStepMantissa < 5) {
        tickStep_ = (int) (tickStepMantissa * 2.) / 2. * magnitudeFactor;
    } else {
        tickStep_ = (int) (tickStepMantissa / 2.) * 2. * magnitudeFactor;
    }

    qint64 firstStep = floor(lower_ / tickStep_);
    qint64 lastStep = ceil(upper_ / tickStep_);

    int tickCount = lastStep - firstStep + 1;

    if (tickCount < 0)
        tickCount = 0;

    ticks_.resize(tickCount);
    labels_.resize(tickCount);

    for (int i = 0; i < tickCount; ++i) {
        ticks_[i] = (firstStep + i) * tickStep_;
        labels_[i] = locale_.toString(ticks_[i], numberFormatChar_.toLatin1(),
                                      numberPrecision_);
    }
}
Esempio n. 4
0
double ProfilePlotView::tickStep(const QCPRange & range, int nSteps)
{
	double step = range.size() / (double)(nSteps+1e-10);
	double factor = qPow(10.0, qFloor(qLn(step) / qLn(10.0)));
	double mantissa = step / factor;

	if (mantissa >= 7)
	{
		factor *= 10.0;
		step = 1;
	}
	else if (mantissa >= 5)
		step = 5;
	else if (mantissa >= 2)
		step = 2;
	else if (mantissa >= 1)
		step = 1;
	else
	{
		factor /= 10.0;
		step = 5;
	}

	return step * factor;
}
Esempio n. 5
0
double Activation_functions::aslog(double arg)
{
    if(arg > 0) {
        return qLn (1 + arg);
    } else {
        return - qLn(1 - arg);
    }
}
void dtkComposerNodeNumberOperatorBinaryLogn::run(void)
{
    double *lhs = d->receiver_lhs.data<double>();
    double *rhs = d->receiver_rhs.data<double>();

    d->value_r = qLn(*lhs) / qLn(*rhs);

    d->emitter.setData<double>(&d->value_r);
}
Esempio n. 7
0
void SourceEditor::linesCountChanged()
{
    int marginWidth = qCeil( qLn( lines() ) / qLn(10) + 0.000001 );

    if (marginWidth != m_marginWidth) {
        m_marginWidth = marginWidth;
        setMarginWidth(NumberMargin, QString(marginWidth, '3') + ' ');
    }
}
Esempio n. 8
0
int ImageProcessor::getEntropyThreshold()
{
    // lazy calculation
    if (!isEntropyCaled) {
        // Make sure histogram is calculate
        getHistogram();

        // Sum of x * log(x) with index below thresholdValue
        double belowSumXLogX = 0;
        // Sum of x * log(x) with index upper than threshold value
        double upperSumXLogX = 0;
        for (int i = 0; i < RANGE_OF_8BITS; ++i)
        {
            if (histogram[i] != 0)
            {
                // Log on base e
                upperSumXLogX += histogram[i] * qLn((double)histogram[i]);
            }
        }

        double maxEntropy = 0;

        for (int thresholdValue = 0; thresholdValue < RANGE_OF_8BITS; ++thresholdValue)
        {
            if (histogram[thresholdValue] == 0)
            {
                continue;
            }

            int upperSum = accHistogram[RANGE_OF_8BITS - 1]
                    - accHistogram[thresholdValue];
            if (upperSum == 0)
            {
                break;
            }

            double xLogX = histogram[thresholdValue] * qLn(histogram[thresholdValue]);
            belowSumXLogX += xLogX;
            upperSumXLogX -= xLogX;

            double belowEntropy = qLn(accHistogram[thresholdValue])
                    - belowSumXLogX / accHistogram[thresholdValue];
            double upperEntropy = qLn(upperSum)
                    - upperSumXLogX / upperSum;
            double entropy = belowEntropy + upperEntropy;

            if (entropy > maxEntropy)
            {
                entropyThreshold = thresholdValue;
                maxEntropy = entropy;
            }
        }
        isEntropyCaled = true;
    }
    return entropyThreshold;
}
int FormatCoordsUnitsStrategyAbstractBase::precisionDigitsForRawNumber (double valueUnformatted,
                                                                        double valueUnformattedOther,
                                                                        bool isXTheta,
                                                                        const DocumentModelGeneral &modelGeneral,
                                                                        const Transformation &transformation) const
{
  LOG4CPP_DEBUG_S ((*mainCat)) << "FormatCoordsUnitsStrategyAbstractBase::precisionDigitsForRawNumber";

  const double PIXEL_SHIFT = 1;
  const int DEFAULT_PRECISION = 5; // Precision used before transformation is available. Equal or greater than x/y pixel counts

  if (transformation.transformIsDefined()) {

    // Measure the resolution if the point is moved some number of pixels in screen coordinates
    QPointF posGraph;
    if (isXTheta) {

      posGraph = QPointF (valueUnformatted,
                          valueUnformattedOther);

    } else {

      posGraph = QPointF (valueUnformattedOther,
                          valueUnformatted);

    }

    QPointF posScreen, posScreenShifted, posGraphShifted;

    transformation.transformRawGraphToScreen (posGraph,
                                              posScreen);

    posScreenShifted = posScreen + QPointF (PIXEL_SHIFT, PIXEL_SHIFT);

    transformation.transformScreenToRawGraph (posScreenShifted,
                                              posGraphShifted);

    double xResolutionPerPixel = (posGraphShifted.x() - posGraph.x()) / PIXEL_SHIFT;
    double yResolutionPerPixel = (posGraphShifted.y() - posGraph.y()) / PIXEL_SHIFT;
    double resolutionPerPixel = (isXTheta ? xResolutionPerPixel : yResolutionPerPixel);

    // Compute number of digits ahead of the decimal point (any single decimal place would work but the decimal point is easiest)
    int powerValue = qFloor (qLn (qAbs (valueUnformatted)) / qLn (10.0));
    int powerResolution = qFloor (qLn (qAbs (resolutionPerPixel)) / qLn (10.0));

    int numberDigitsForResolution = powerValue - powerResolution + 1 + modelGeneral.extraPrecision();

    return numberDigitsForResolution + 1; // Add one just to be safe

  } else {

    return DEFAULT_PRECISION;
  }
}
Esempio n. 10
0
QString f3_operation_speed(const QString& operation,qint64 blockSize)
{
    int p = operation.indexOf('/');
    int operationSec = - f3_operation_time(operation.left(p)).secsTo(QTime(0,0,0,0));
    if (operationSec == 0)
        return "";
    qint64 blockCount = operation.mid(p + 1, operation.indexOf('=') - p - 1).toInt();
    float speed = blockCount * blockSize / operationSec;
    int grade = qLn(speed) / qLn(1000);
    return QString::number((speed / qPow(1000, grade)))
            .append(' ')
            .append(f3_capacity_unit(grade))
            .append("/s");
}
Esempio n. 11
0
QSet<TileId> PlacemarkLayout::visibleTiles( const ViewportParams *viewport )
{
    int zoomLevel = qLn( viewport->radius() *4 / 256 ) / qLn( 2.0 );

    /*
     * rely on m_placemarkCache to find the placemarks for the tiles which
     * matter. The top level tiles have the more popular placemarks,
     * the bottom level tiles have the smaller ones, and we only get the ones
     * matching our latLonAltBox.
     */

    qreal north, south, east, west;
    viewport->viewLatLonAltBox().boundaries(north, south, east, west);
    QSet<TileId> tileIdSet;
    QVector<QRectF> geoRects;
    if( west <= east ) {
        geoRects << QRectF(west, north, east - west, south - north);
    } else {
        geoRects << QRectF(west, north, M_PI - west, south - north);
        geoRects << QRectF(-M_PI, north, east + M_PI, south - north);
    }
    foreach( const QRectF &geoRect, geoRects ) {
        TileId key;
        QRect rect;

        key = TileId::fromCoordinates( GeoDataCoordinates(geoRect.left(), north, 0), zoomLevel);
        rect.setLeft( key.x() );
        rect.setTop( key.y() );

        key = TileId::fromCoordinates( GeoDataCoordinates(geoRect.right(), south, 0), zoomLevel);
        rect.setRight( key.x() );
        rect.setBottom( key.y() );

        TileCoordsPyramid pyramid(0, zoomLevel );
        pyramid.setBottomLevelCoords( rect );

        for ( int level = pyramid.topLevel(); level <= pyramid.bottomLevel(); ++level ) {
        QRect const coords = pyramid.coords( level );
        int x1, y1, x2, y2;
        coords.getCoords( &x1, &y1, &x2, &y2 );
            for ( int x = x1; x <= x2; ++x ) {
                for ( int y = y1; y <= y2; ++y ) {
                    TileId const tileId( 0, level, x, y );
                    tileIdSet.insert(tileId);
                }
            }
        }
    }
Esempio n. 12
0
/**
 * @brief MathFunctions::normalCDFInverse computes the inverse of the normal cumulative distribution function
 * @param p The value on which is applied the function
 * @return The inverse of the normal cumulative distribution function value
 */
double MathFunctions::normalCDFInverse(double p) {
	if (p <= 0.0 || p >= 1.0) {
		QString os;
		os = "Invalid input argument (" + QString::number(p) + "); must be larger than 0 but less than 1.";
		throw std::invalid_argument(os.toStdString().c_str());
	}

	if (p < 0.5) {
		// F^-1(p) = - G^-1(p)
		return -rationalApproximation(qSqrt(-2.0*qLn(p)));
	}
	else {
		// F^-1(p) = G^-1(1-p)
		return rationalApproximation(qSqrt(-2.0*qLn(1-p)));
	}
}
Esempio n. 13
0
double RasterData::value(double x, double y) const
{
  if (x >= 0 && x < Statistic::SCREEN_SIZE &&
      y >= 0 && y < Statistic::SCREEN_SIZE)
    return d[qFloor(x)][qFloor(y)] > 0 ? qLn(d[qFloor(x)][qFloor(y)]) : 0.0;
  return 0.0;
}
Esempio n. 14
0
qreal PasswordChecker::entropy(const QString &str) {
    static const int Range = 256;
    const QByteArray &sample = str.toLatin1();
    QVector<int> histo(Range, 0);
    for (int i = 0; i < sample.size(); ++i) {
        ++histo[static_cast<uchar>(sample.at(i))];
    }
    qreal ent = 0;
    const qreal l = sample.size();
    for (int i = 0; i < Range; ++i) {
        const qreal p = qreal(histo[i]) / l;
        if (p > 0)
            ent += p * M_LOG2E * qLn(1.0 / p);
    }
    const qreal bitsPerVariate = qLn(qreal(Range)) * M_LOG2E;
    return ent / bitsPerVariate;
}
Esempio n. 15
0
void MainWindow::integerTickStepCase_yRangeChanged(QCPRange newRange)
{
	// Generate tick positions according to linear scaling:
	double mTickStep = newRange.size()/(double)(5+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers
	double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
	double tickStepMantissa = mTickStep/magnitudeFactor;
	if (tickStepMantissa < 5)
	{
		// round digit after decimal point to 0.5
		mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor;
	} else
	{
		// round to first digit in multiples of 2
		mTickStep = (int)((tickStepMantissa/10.0)*5)/5.0*10*magnitudeFactor;
	}
	mCustomPlot->yAxis->setTickStep(qCeil(mTickStep));
}
qreal UltimateTicTacToeMontecarloAI::nodeUCBValue(Node const& node, Nodes const& nodes) const {
  if(node.parent != -1)
  {
    return node.v + c * qSqrt(qLn(nodes.at(node.parent).n) / node.n);
  } else {
    return 0;
  }
}
Esempio n. 17
0
qreal FuzzyNode::get_d_b(int feature_id, int fuzzy_id)
{
    auto& x = *(_inputs[feature_id]);
    auto& a = _fuzzy_set_params[fuzzy_id][feature_id][0];
    auto& b = _fuzzy_set_params[fuzzy_id][feature_id][1];
    auto& c = _fuzzy_set_params[fuzzy_id][feature_id][2];
    return -2*qPow(qAbs((a-x)/c),2*b)*qLn(qAbs((a-x)/c))/qPow((qPow(qAbs((a-x)/c),2*b)+1),2);
}
Esempio n. 18
0
     void Calculator::calculate()
     {

     double operand2     = m_stk.pop().toDouble();
     QString strOperation = m_stk.pop();
     double operand1     = m_stk.pop().toDouble();
     double Result_d     = 0;
     if (strOperation == "+") {
     Result_d  = operand1+operand2;
     }
     if (strOperation == "-")
     {
     Result_d  = operand1-operand2;
     }
     if (strOperation == "/")
     {
     Result_d  = operand1 / operand2;
     }
     if (strOperation == "*")
     {
     Result_d  = operand1 * operand2;
     }
     if (strOperation == "Pow")
     {
       Result_d=qPow(operand1,operand2);
     }
     if (strOperation == "M-")
     {
     subs_memory(operand1);
     }
     if (strOperation == "M+")
     {
     add_memory(operand1);
     }
     if (strOperation == "MS")
     {
     reset_memory();
     }
     if (strOperation == "Sqrt")
     {
     Result_d=qSqrt(operand1);
     }
     if (strOperation == "ln")
     {
     Result_d=qLn(operand1);
     }
     if (strOperation == "MR")
     {
      Result_d=get_memory();

     }
     if (strOperation == "abs")
     {
      Result_d=qAbs(operand1);

     }
     m_plcd->display(Result_d );
     }
Esempio n. 19
0
void MainWindow:: equals()
{
    sNum = value.toDouble();

    if (addBool){
        total = QString::number(fNum+sNum);
        label -> setText(total);
    }
    if (subtractBool){
        total = QString::number(fNum-sNum);
        label -> setText(total);
    }
    if (multiplyBool){
        total = QString::number(fNum*sNum);
        label -> setText(total);
    }
    if(divideBool){
        total = QString::number(fNum/sNum);
        label -> setText(total);
    }
    if(sinBool){
        total = QString::number(qSin(fNum));
        label -> setText(total);
    }
    if(cosBool){
        total = QString::number(qCos(fNum));
        label -> setText(total);
    }
    if(tanBool){
        total = QString::number(qTan(fNum));
        label -> setText(total);
    }
    if(sqrtBool){
        total = QString::number(qSqrt(fNum));
        label -> setText(total);
    }
    if(powBool){
        total = QString::number(qPow(fNum,2));
        label -> setText(total);
    }
    if(cubicBool){
        total = QString::number(qPow(fNum,3));
        label -> setText(total);
    }
    if(expBool){
        total = QString::number(qExp(fNum));
        label -> setText(total);
    }
    if(lnBool){
        total = QString::number(qLn(fNum));
        label -> setText(total);
    }

    fNum = 0;
    sNum = 0;
}
Esempio n. 20
0
void RasterData::flush()
{
  QwtInterval zInterval(0.0, qMax(qLn(max), 1.0));
  setInterval(Qt::ZAxis, zInterval);

  QwtScaleWidget *rightAxis = s->axisWidget(QwtPlot::yRight);
  rightAxis->setColorMap(zInterval, new ColorMap());

  s->setAxisScale(QwtPlot::yRight, 0.0, zInterval.maxValue());
}
Esempio n. 21
0
Rpn::Operand NaturalLogarithm::calculate(FunctionCalculator *calculator, QList<Rpn::Operand> actualArguments)
{
	Q_UNUSED(calculator);

	Rpn::Operand result;
	result.type = Rpn::OperandNumber;
	result.value = qLn(actualArguments.at(0).value.value<Number>());

	return result;
}
Esempio n. 22
0
/*!
    Starts scrolling the widget so that the point \a pos is visible inside
    the viewport.

    If the specified point cannot be reached, the contents are scrolled to the
    nearest valid position (in this case the scroller might or might not overshoot).

    The scrolling speed will be calculated so that the given position will
    be reached after a platform-defined time span (1 second for Maemo 5).
    The final speed at the end position is not guaranteed to be zero.

    \sa ensureVisible(), maximumContentPosition()
*/
void QKineticScroller::scrollTo(const QPointF &pos, int scrollTime)
{
    Q_D(QKineticScroller);

    if (scrollTime <= 0)
        scrollTime = 1;

    qKSDebug() << "QKS::scrollTo(" << pos << " [pix], " << scrollTime << " [ms])";

    qreal time = qreal(scrollTime) / 1000;

    if ((pos == contentPosition()) ||
            (d->state == QKineticScroller::StatePressed) ||
            (d->state == QKineticScroller::StateDragging)) {
        return;
    }

    // estimate the minimal start velocity
    // if the start velocity is below that then the scrolling would stop before scrollTime.
    //qreal vMin = d->linearDecelerationFactor * time / qPow(d->exponentialDecelerationBase, time);

    /*
    // estimate of the distance passed within the vMin time during scrollTime
    qreal distMin = qreal(scrollTime) * vMin / 2.0;

    QPointF v = QPointF((pos.x()-contentPosition().x()) / distMin * vMin,
                        (pos.y()-contentPosition().y()) / distMin * vMin);

    */

    // v(t) = vstart * exponentialDecelerationBase ^ t - linearDecelerationFactor * t
    // pos(t) = integrate(v(t) * dt)
    // pos(t) = vstart * (eDB ^ t / ln(eDB) + C) -  lDF / 2 * t ^ 2
    //
    // pos(time) = pos - contentsPos()
    // vstart = ((lDF / 2) * time ^ 2 + (pos - contentPos())) / (eDB ^ time / ln(eDB) + C)
    // (for C = -1/ln(eDB) )

    QPointF scrollDir(qSign(pos.x() - contentPosition().x()),
                      qSign(pos.y() - contentPosition().y()));

    QPointF v = (scrollDir * (d->linearDecelerationFactor / qreal(2)) * qreal(time) * qreal(time) + (pos - contentPosition()) / d->pixelPerMeter);
    if (d->exponentialDecelerationBase != qreal(1))
        v /= (qPow(d->exponentialDecelerationBase, time) - 1) / qLn(d->exponentialDecelerationBase);
    else
        v /= time;

    d->scrollToPosition = pos;
    d->scrollToX = true;
    d->scrollToY = true;
    d->releaseVelocity = v;
    d->scrollRelativeTimer.restart();
    d->scrollAbsoluteTimer.restart();
    d->setState(QKineticScroller::StateScrolling);
}
Esempio n. 23
0
void ContTblPlugin::processRR(QString allele, QVector<QString> names, QVector<int> numH, QVector<int> numI)
{
    double a, b, c, d; // коэфф таблицы сопряж.

    a = 0;
    b = 0;
    c = 0;
    d = 0;

    for (int i = 0; i < names.size(); ++i)
    {
        if (allele == names[i])
        {
            a += numH[i];
            c += numI[i];
        }
        else
            {
                b += numH[i];
                d += numI[i];
            }
    }
    qDebug() << allele << ": a = " << a << "d = " << d << "b =" << b << "c = " << c;
    if (a * b * c * d == 0)
    {
        a = a + 0.5;
        b = b + 0.5;
        c = c + 0.5;
        d = d + 0.5;
    }

    RR = (double) (b * c) / (a * d); // в статье сытина ошибка

    double left, right;
    double V;

    V = 1.96 * qSqrt(1.0 / a + 1.0 / b + 1.0 / c + 1.0 / d);
    left = qExp(qLn(RR) - V); // тоже не указано в статье, но в проге почемуто делаем e^(qLn(RR) - 1.96 * qSqrt(1.0 / a + 1.0 / b + 1.0 / c + 1.0 / d))
    right = qExp(qLn(RR) + V);

    confInt = "[" + QString::number(left) + " ; " + QString::number(right) + "]";
}
Esempio n. 24
0
qreal CanvasContainer::calculateFactor(qreal current, bool zoomIn)
{
    if (current <= MIN_SCALE_FACTOR && !zoomIn)
        return MIN_SCALE_FACTOR;
    if (current >= MAX_SCALE_FACTOR && zoomIn)
        return MAX_SCALE_FACTOR;
    if (current < 1)
    {
        qreal power = qLn(current) / qLn(0.5);
        int newPower = qFloor(power);
        if (zoomIn)
        {
            if (qFuzzyCompare(qreal(newPower), power))
                newPower--;
            return qBound(MIN_SCALE_FACTOR, qPow(0.5, newPower), MAX_SCALE_FACTOR);
        }
        else
        {
            return qBound(MIN_SCALE_FACTOR, qPow(0.5, newPower + 1), MAX_SCALE_FACTOR);
        }
    }
    else
    {
        qreal newScale = qFloor(current);
        if (zoomIn)
        {
            return qBound(MIN_SCALE_FACTOR, newScale + 1, MAX_SCALE_FACTOR);
        }
        else
        {
            if (qFuzzyCompare(newScale, current))
                newScale--;
            if (qFuzzyCompare(newScale, 0.0))
                newScale = 0.5;
            return qBound(MIN_SCALE_FACTOR, newScale, MAX_SCALE_FACTOR);
        }

    }
}
Esempio n. 25
0
void MainWindow::setupAdaptiveSamplingTest(QCustomPlot *customPlot)
{
	qsrand(1);
	QCPGraph *g = customPlot->addGraph();
	int n = 200000;
	QVector<double> x, y;
	x << -6;
	y << 2;
	for (int i=0; i<n/2; ++i)
	{
		x << i/(double)(n/2-1)*4-5;
		if (qrand()%(n/25) == 0)
			y << qrand()/(double)RAND_MAX*7; // generate outliers (must be preserved in adaptive-sampling-algorithm)
		else
			y << qCos(qrand()/(double)RAND_MAX*2*M_PI)*qSqrt(-2*qLn(qrand()/(double)RAND_MAX)) + 5*qSin(x[i]);
	}
	x << 0.5;
	y << 2;
	for (int i=0; i<n/2; ++i)
	{
		x << i/(double)(n/2-1)*4+1;
		if (qrand()%(n/25) == 0)
			y << qrand()/(double)RAND_MAX*7; // generate outliers (must be preserved in adaptive-sampling-algorithm)
		else
			y << qCos(qrand()/(double)RAND_MAX*2*M_PI)*qSqrt(-2*qLn(qrand()/(double)RAND_MAX)) + qSin(5*x[i]);
	}
	x << 6;
	y << -1;
	g->setData(x, y);
	//g->setScatterStyle(QCPScatterStyle::ssPlus);
	//g->setLineStyle(QCPGraph::lsNone);
	g->setAdaptiveSampling(true);

	customPlot->setPlottingHint(QCP::phFastPolylines, true);
	customPlot->rescaleAxes();
	customPlot->xAxis->scaleRange(1, customPlot->xAxis->range().center());
	customPlot->yAxis->scaleRange(1, customPlot->yAxis->range().center());
}
Esempio n. 26
0
qreal PlotAxes::findTickIncrement(qreal range, qreal size,
  qreal minTickSpacing) {
  qreal tmp = minTickSpacing * range / size;

  qreal logIncrement = qCeil(qLn(tmp) / LN10);
  qreal increment = qExp(logIncrement * LN10);

  qreal pxPerTick = increment * size / range;

  if (pxPerTick > 5 * minTickSpacing) {
    return increment / 5;
  } else if (pxPerTick > 2 * minTickSpacing) {
    return increment / 2;
  } else {
    return increment;
  }
}
Esempio n. 27
0
qreal KMath::k0(qreal x)
{
    qreal y,ans;

    if (x <= 2.0) {
        y=x*x/4.0;
        ans=(-qLn(x/2.0)*KMath::i0(x))+(-0.57721566+y*(0.42278420
        +y*(0.23069756+y*(0.3488590e-1+y*(0.262698e-2
        +y*(0.10750e-3+y*0.74e-5))))));
    } else {
        y=2.0/x;
        ans=(qExp(-x)/qSqrt(x))*(1.25331414+y*(-0.7832358e-1
        +y*(0.2189568e-1+y*(-0.1062446e-1+y*(0.587872e-2
        +y*(-0.251540e-2+y*0.53208e-3))))));
    }
    return ans;
}
Esempio n. 28
0
void SpectrumAnalyserThread::calculateSpectrum(const QByteArray &buffer,
                                                int inputFrequency,
                                                int bytesPerSample)
{
#ifndef DISABLE_FFT
    Q_ASSERT(buffer.size() == m_numSamples * bytesPerSample);

    // Initialize data array
    const char *ptr = buffer.constData();
    for (int i=0; i<m_numSamples; ++i) {
        const qint16 pcmSample = *reinterpret_cast<const qint16*>(ptr);
        // Scale down to range [-1.0, 1.0]
        const DataType realSample = pcmToReal(pcmSample);
        const DataType windowedSample = realSample * m_window[i];
        m_input[i] = windowedSample;
        ptr += bytesPerSample;
    }

    // Calculate the FFT
    m_fft->calculateFFT(m_output.data(), m_input.data());

    // Analyze output to obtain amplitude and phase for each frequency
    for (int i=2; i<=m_numSamples/2; ++i) {
        // Calculate frequency of this complex sample
        m_spectrum[i].frequency = qreal(i * inputFrequency) / (m_numSamples);

        const qreal real = m_output[i];
        qreal imag = 0.0;
        if (i>0 && i<m_numSamples/2)
            imag = m_output[m_numSamples/2 + i];

        const qreal magnitude = qSqrt(real*real + imag*imag);
        qreal amplitude = SpectrumAnalyserMultiplier * qLn(magnitude);

        // Bound amplitude to [0.0, 1.0]
        m_spectrum[i].clipped = (amplitude > 1.0);
        amplitude = qMax(qreal(0.0), amplitude);
        amplitude = qMin(qreal(1.0), amplitude);
        m_spectrum[i].amplitude = amplitude;
    }
#endif

    emit calculationComplete(m_spectrum);
}
void EasySelectorWidget::redrawBackground(void)
{
  Q_D(EasySelectorWidget);
  if (width() == 0 || height() == 0) {
    d->background = QPixmap();
    return;
  }
  const int nX = d->maxLength - d->minLength + 1;
  const int nY = Password::MaxComplexity + 1;
  const int xs = width() / nX;
  const int ys = height() / nY;
  d->background = QPixmap(QSize(xs * nX + 1, ys * nY + 1));
  QPainter p(&d->background);
  for (int y = 0; y < nY; ++y)
    for (int x = 0; x < nX; ++x)
      p.fillRect(QRect(x * xs, d->background.height() - y * ys - ys, xs, ys),
                 red2yellow2green(qLn(passwordStrength(x + d->minLength, y)) / 40).darker(168));
  p.setBrush(Qt::transparent);
  p.setPen(QPen(QBrush(QColor(0, 0, 0, 128)), 1));
  for (int x = 0; x <= nX; ++x)
    p.drawLine(xs * x, 0, xs * x, d->background.height());
  for (int y = 0; y <= nY; ++y)
    p.drawLine(0, ys * y, d->background.width(), ys * y);
}
void dtkComposerNodeNumberOperatorUnaryLog10::run(void)
{
    double *value = d->receiver.data<double>();
    *value = qLn(*value) / qLn(10.);
    d->emitter.setData<double>(value);
}