Example #1
0
void Normalization::fit(int k, int p, int iLength, double arr[], double cof[], KstVectorPtr vector_out)
{
  if(k+p < iLength)
  {
    double v1[p];
    double v2[p];
    int j=0;

    for(int i=k; i<k+p; i++)
    {
      v1[j] = (double)i;
      v2[j] = arr[i];
      j++;
    }

    double c0, c1, cov00, cov01, cov11, chisq;

    gsl_fit_linear(v1, 1, v2, 1, p, &c0, &c1, &cov00, &cov01, &cov11, &chisq);
    cof[0] = c0;
    cof[1] = c1;
    for(int i=k; i<k+p; i++)
    {
      vector_out->value()[i] = cof[0]+cof[1]*i;
    }
  }
  else
  {
    for(int i=k; i<iLength; i++)
    {
      vector_out->value()[i] = cof[0]+cof[1]*i;
    }
  }
}
Example #2
0
//swap input vector
bool Reverse::algorithm() {

  KstVectorPtr input = inputVector(INPUT);
  KstVectorPtr output  = outputVector(OUTPUT);
  output->resize(input->length());
  int length = input->length();

  for (int i = 0; i < length; i++){
    output->value()[length-i-1] = input->value()[i];
  }

  return true;
}
Example #3
0
// FIXME: KstPlugin should not know about fit scalars!!
void KstPlugin::createFitScalars() {
  if (_plugin->data()._isFit && _outputVectors.contains("Parameters")) {
    KstVectorPtr vectorParam = _outputVectors["Parameters"];
    if (vectorParam) {
      QString paramName;
      int i = 0;
      int length = vectorParam->length();

      for (paramName = _plugin->parameterName(i); 
          !paramName.isEmpty() && i < length; 
           paramName = _plugin->parameterName(++i)) {
        double scalarValue = vectorParam->value(i);
        if (!_outputScalars.contains(paramName)) {
          QString scalarName = i18n("%1-%2").arg(tagName()).arg(paramName);
          KstScalarPtr s = new KstScalar(scalarName, scalarValue);
          s->writeLock();
          s->setProvider(this);
          s->writeUnlock();
          _outputScalars.insert(paramName, s);
        } else {
          _outputScalars[paramName]->setValue(scalarValue);
        }
      }
    }
  }
}
Example #4
0
// FIXME: KstPlugin should not know about fit scalars!!
void KstPlugin::createFitScalars() {
  // Assumes that this is called with a write lock in place on this object
  if (_plugin->data()._isFit && _outputVectors.contains("Parameters")) {
    KstVectorPtr vectorParam = _outputVectors["Parameters"];
    if (vectorParam) {
      QString paramName;
      int i = 0;
      int length = vectorParam->length();

      for (paramName = _plugin->parameterName(i); 
          !paramName.isEmpty() && i < length; 
           paramName = _plugin->parameterName(++i)) {
        double scalarValue = vectorParam->value(i);
        if (!_outputScalars.contains(paramName)) {
          QString scalarName = i18n("%1-%2").arg(tagName()).arg(paramName);
          KstScalarPtr s = new KstScalar(scalarName, this, scalarValue);
          s->KstObject::writeLock();
          _outputScalars.insert(paramName, s);
          ++_outScalarCnt;
        } else {
          _outputScalars[paramName]->setValue(scalarValue);
        }
      }
    }
  }
}
void KstCPlugin::createFitScalars() {
  Q_ASSERT(myLockStatus() == KstRWLock::WRITELOCKED);
  // Assumes that this is called with a write lock in place on this object

  if (_plugin->data()._isFit && _outputVectors.contains("Parameters")) {
    KstVectorPtr vectorParam = _outputVectors["Parameters"];
    if (vectorParam) {
      QString paramName;
      int i = 0;
      int length = vectorParam->length();

      KstWriteLocker blockScalarUpdates(&KST::scalarList.lock());
      KST::scalarList.setUpdateDisplayTags(false);
      for (paramName = _plugin->parameterName(i); 
          !paramName.isEmpty() && i < length; 
           paramName = _plugin->parameterName(++i)) {
        double scalarValue = vectorParam->value(i);
        if (!_outputScalars.contains(paramName)) {
          KstScalarPtr s = new KstScalar(KstObjectTag(paramName, tag()), this, scalarValue);
          s->KstObject::writeLock();  // must write lock, since fit scalars are created from update()
          _outputScalars.insert(paramName, s);
          ++_outScalarCnt;
        } else {
          _outputScalars[paramName]->setValue(scalarValue);
        }
      }
      KST::scalarList.setUpdateDisplayTags(true);
    }
  }
}
Example #6
0
int KST::vectorToFile(KstVectorPtr v, QFile *f) {
int rc = 0;
#define BSIZE 128
char buf[BSIZE];
int _size = v->length();
double *_v = v->value();
register int modval;
KProgressDialog *kpd = new KProgressDialog(0L, "vector save", i18n("Saving Vector"), i18n("Saving vector %1...").arg(v->tagName()));

  kpd->setAllowCancel(false);

  kpd->progressBar()->setTotalSteps(_size);
  kpd->show();

  modval = QMAX(_size/100, 100);

  for (int i = 0; i < _size; i++) {
    int l = snprintf(buf, BSIZE, "%d %g\n", i, _v[i]);
    f->writeBlock(buf, l);
    if (i % 100 == 0) {
      kpd->progressBar()->setProgress(i);
      kapp->processEvents();
    }
  }
  kpd->progressBar()->setProgress(_size);

delete kpd;

#undef BSIZE
return rc;
}
Example #7
0
// Remove some elements from the vector starting from vector[0]
bool Trim::algorithm() {
  KstVectorPtr input = inputVector(INPUT);
  KstScalarPtr remove = inputScalar(REMOVE);
  KstVectorPtr cut = outputVector(CUT);
  bool rc = false;

  if (input->length() > remove->value()) {
    int cutSize = (int)input->length() - (int)remove->value();
    cut->resize( cutSize, false );
    for (int j=0; j<cutSize; j++) {
      cut->value()[j] = input->value()[(int)remove->value()+j];
    }

    rc = true;
  }

  return rc;
}
Example #8
0
bool NoiseAddition::algorithm() {
  KstVectorPtr array    = inputVector(ARRAY);
  KstScalarPtr sigma    = inputScalar(SIGMA);
  KstVectorPtr output   = outputVector(OUTPUT);

  const gsl_rng_type* pGeneratorType;
  gsl_rng* pRandomNumberGenerator;
  double* pResult[1];
  int iRetVal = false;
  int iLength = array->length();

  pResult[0] = 0L;

  if (iLength > 0) {
    if (output->length() != iLength) {
      output->resize(iLength, false);
      pResult[0] = (double*)realloc( output->value(), iLength * sizeof( double ) );
    } else {
      pResult[0] = output->value();
    }
  }

  pGeneratorType = gsl_rng_default;
  pRandomNumberGenerator = gsl_rng_alloc( pGeneratorType );
  if (pRandomNumberGenerator != NULL) {
    if (pResult[0] != NULL) {
      for (int i=0; i<iLength; i++) {
        output->value()[i] = array->value()[i] + gsl_ran_gaussian( pRandomNumberGenerator, sigma->value() );
      }

      iRetVal = true;
    }
    gsl_rng_free( pRandomNumberGenerator );
  }

  return iRetVal;
}
bool Differentiation::algorithm() {

  KstVectorPtr inputvector  = inputVector(INPUTVECTOR);
  KstScalarPtr time_step    = inputScalar(TIME_STEP);
  KstVectorPtr derivative   = outputVector(DERIVATIVE);

  /* Memory allocation */
  if (derivative->length() != inputvector->length()) {
    derivative->resize(inputvector->length(), true);
  }

  derivative->value()[0] = (inputvector->value()[1] - inputvector->value()[0]) / time_step->value();

  int i = 1;
  for (; i < inputvector->length()-1; i++) {
      derivative->value()[i] = (inputvector->value()[i+1] - inputvector->value()[i-1])/(2*time_step->value());
  }

  derivative->value()[i] = (inputvector->value()[i] - inputvector->value()[i-1]) / time_step->value();

  return true;
}
Example #10
0
void KstVectorTable::paintCell( QPainter* painter, int row, int col, const QRect& cr, bool selected, const QColorGroup& cg ) {
  KstVectorPtr vector = *KST::vectorList.findTag(_strVector);
  QString str;

  painter->eraseRect( 0, 0, cr.width(), cr.height() );
  if (selected) {
    painter->fillRect( 0, 0, cr.width(), cr.height(), cg.highlight() );
    painter->setPen(cg.highlightedText());
  } else {
    painter->fillRect( 0, 0, cr.width(), cr.height(), cg.base() );
    painter->setPen(cg.text());
  }

  if( col == 0 && vector) {
    str.setNum(vector->value(row), 'g', 16);
  }

  painter->drawText(0, 0, cr.width(), cr.height(), AlignLeft, str);
}
Example #11
0
bool CumulativeSum::algorithm() {

  KstVectorPtr inputvector    = inputVector(INPUTVECTOR);
  KstScalarPtr scale_factor   = inputScalar(SCALE_FACTOR);
  KstVectorPtr cumulative_sum = outputVector(CUMULATIVE_SUM);

  /* Memory allocation */
  if (cumulative_sum->length() != inputvector->length()) {
    cumulative_sum->resize(inputvector->length()+1, true);
  }

  cumulative_sum->value()[0] = 0.0;

  for (int i = 0; i < inputvector->length(); i++) {
    cumulative_sum->value()[i+1] =
      inputvector->value()[i]*scale_factor->value() + cumulative_sum->value()[i];
  }

  return true;
}
Example #12
0
KstVectorPtr KstVector::generateVector(double x0, double x1, int n, const QString &tag) {
    if (n < 2) {
        n = 2;
    }

    if (x0 > x1) {
        double tx;
        tx = x0;
        x0 = x1;
        x1 = tx;
    }

    if (x0 == x1) {
        x1 = x0 + 0.1;
    }

    QString t = tag;
    if (t.isEmpty()) {
        KST::vectorList.lock().readLock();
        t = "V" + QString::number(KST::vectorList.count() + 1) + "-" + "X(" + QString::number(x0) + ".." + QString::number(x1) + ")";
        KST::vectorList.lock().readUnlock();
    }

    while (KST::vectorTagNameNotUnique(t, false)) {
        t += "'";
    }

    KstVectorPtr xv = new KstVector(t, n);

    for (int i = 0; i < n; i++) {
        xv->value()[i] = x0 + double(i) * (x1 - x0) / (n - 1);
    }

    xv->_scalars["min"]->setValue(x0);
    xv->_scalars["max"]->setValue(x1);
    xv->UpdateScalars();

    return xv;
}
Example #13
0
int KST::vectorToFile(KstVectorPtr v, QFile *f) {
  KstApp *app = KstApp::inst();
#define BSIZE 128
  char buf[BSIZE];

  v->readLock();

  int vSize = v->length();
  double *value = v->value();
  register int modval;
  QString saving = i18n("Saving vector %1").arg(v->tagName());

  modval = QMAX(vSize/100, 100);

  QString ltxt = "; " + v->tagName() + '\n';
  f->writeBlock(ltxt.ascii(), ltxt.length());
  ltxt.fill('-');
  ltxt[0] = ';';
  ltxt[1] = ' ';
  ltxt[ltxt.length() - 1] = '\n';
  f->writeBlock(ltxt.ascii(), ltxt.length());

  app->slotUpdateProgress(vSize, 0, QString::null);

  for (int i = 0; i < vSize; i++) {
    int l = snprintf(buf, BSIZE, "%.15g\n", value[i]);
    f->writeBlock(buf, l);
    if (i % modval == 0) {
      app->slotUpdateProgress(vSize, i, saving);
    }
  }

  v->readUnlock();

  app->slotUpdateProgress(0, 0, QString::null);

#undef BSIZE
  return 0;
}
Example #14
0
bool Phase::algorithm() {

  KstVectorPtr time     = inputVector(TIME);
  KstVectorPtr data_i   = inputVector(DATA_I);
  KstScalarPtr period   = inputScalar(PERIOD);
  KstScalarPtr zero     = inputScalar(ZERO);
  KstVectorPtr phase    = outputVector(PHASE);
  KstVectorPtr data_o   = outputVector(DATA_O);

  double* pResult[2];
  double  dPhasePeriod = period->value();
  double dPhaseZero = zero->value();
  int iLength;

  bool iRetVal = false;

  if (dPhasePeriod > 0.0) {
    if (time->length() == data_i->length()) {
      iLength = time->length();

      if (phase->length() != iLength) {
        phase->resize(iLength, true);
        pResult[0] = (double*)realloc( phase->value(), iLength * sizeof( double ) );
      } else {
        pResult[0] = phase->value();
      }

      if (data_o->length() != iLength) {
        data_o->resize(iLength, true);
        pResult[1] = (double*)realloc( data_o->value(), iLength * sizeof( double ) );
      } else {
        pResult[1] = data_o->value();
      }

      if (pResult[0] != NULL && pResult[1] != NULL) {
        for (int i = 0; i < phase->length(); ++i) {
          phase->value()[i] = pResult[0][i];
        }
        for (int i = 0; i < data_o->length(); ++i) {
          data_o->value()[i] = pResult[1][i];
        }

        /*
        determine the phase...
        */
        for (int i=0; i<iLength; i++) {
          phase->value()[i] = fmod( ( time->value()[i] - dPhaseZero ) / dPhasePeriod, 1.0 );
        }

        /*
        sort by phase...
        */
        memcpy( data_o->value(), data_i->value(), iLength * sizeof( double ) );
        double* sort[2];
        sort[0] = phase->value();
        sort[1] = data_o->value();
        quicksort( sort, 0, iLength-1 );

        iRetVal = true;
      }
    }
  }

  return iRetVal;
}
Example #15
0
bool Normalization::algorithm() {
  KstVectorPtr vectorIn = inputVector(VECTOR_IN);
  KstVectorPtr vectorOut = outputVector(VECTOR_OUT);
  double *arr;
  double *Yi;
  int iLength = vectorIn->length();
  int w = 1;

  arr = new double[iLength];
  Yi = new double[iLength];

  for(int i=0; i<iLength; i++)
  {
    Yi[i] = vectorIn->value()[i];
  }

  //
  // exclude peak values
  //
  for(int loop=0; loop<2; loop++)
  {
    for(int i=0; i<iLength; i++)
    {
      arr[i] = Yi[i];
    }

    for(int i=0; i<iLength; i++)
    {
      if(isMin(Yi, i, iLength) || isMax(Yi, i, iLength))
      {
        excludePts(arr, i, w, iLength);
      }
    }

    searchHighPts(arr, iLength);
    interpolate(Yi, arr, iLength);
  }

  //
  // do a piecewise linear fit
  //
  vectorOut->resize(iLength, false);

  int L = 3;
  double cof[2] = { 0.0, 0.0 };

  for(int i=0; i<iLength; i=i+L)
  {
    fit(i, L, iLength, Yi, cof, vectorOut);
  }

  //
  // normalize
  //
  for(int i=0; i<iLength; i++)
  {
    vectorOut->value()[i] = vectorIn->value()[i] / vectorOut->value()[i];
  }

  //
  // exclude off points
  //
  for(int i=0; i<iLength; i++)
  {
    if(vectorOut->value()[i] < 0.0 || vectorOut->value()[i] > 1.2)
    {
      vectorOut->value()[i] = NOPOINT;
    }
  }

  delete[] arr;
  delete[] Yi;

  return true;
}
bool CrossCorrelate::algorithm() {

  KstVectorPtr array_one    = inputVector(ARRAY_ONE);
  KstVectorPtr array_two    = inputVector(ARRAY_TWO);
  KstVectorPtr step_value   = outputVector(STEP_VALUE);
  KstVectorPtr correlated   = outputVector(CORRELATED);

  if (array_one->length() <= 0               ||
      array_two->length() <= 0               ||
      array_one->length() != array_two->length()) {
      return false;
  }

  double* pdArrayOne;
  double* pdArrayTwo;
  double* pdResult[2];
  double  dReal;
  double  dImag;

  int iLength;
  int iLengthNew;

  bool iReturn = false;

  //
  // zero-pad the array...
  //
  iLength  = array_one->length();
  iLength *= 2;

  step_value->resize(array_one->length(), false);
  correlated->resize(array_two->length(), false);

  //
  // round iLength up to the nearest power of two...
  //
  iLengthNew = 64;
  while( iLengthNew < iLength && iLengthNew > 0) {
    iLengthNew *= 2;
  }
  iLength = iLengthNew;

  if (iLength <= 0)
    return false;

  pdArrayOne = new double[iLength];
  pdArrayTwo = new double[iLength];
  if (pdArrayOne != NULL && pdArrayTwo != NULL) {
    //
    // zero-pad the two arrays...
    //
    memset( pdArrayOne, 0, iLength * sizeof( double ) );
    memcpy( pdArrayOne, array_one->value(), array_one->length() * sizeof( double ) );

    memset( pdArrayTwo, 0, iLength * sizeof( double ) );
    memcpy( pdArrayTwo, array_two->value(), array_two->length() * sizeof( double ) );

    //
    // calculate the FFTs of the two functions...
    //
    if (gsl_fft_real_radix2_transform( pdArrayOne, 1, iLength ) == 0) {
      if (gsl_fft_real_radix2_transform( pdArrayTwo, 1, iLength ) == 0) {
        //
        // multiply one FFT by the complex conjugate of the other...
        //
        for (int i=0; i<iLength/2; i++) {
          if (i==0 || i==(iLength/2)-1) {
            pdArrayOne[i] = pdArrayOne[i] * pdArrayTwo[i];
          } else {
            dReal = pdArrayOne[i] * pdArrayTwo[i] + pdArrayOne[iLength-i] * pdArrayTwo[iLength-i];
            dImag = pdArrayOne[i] * pdArrayTwo[iLength-i] - pdArrayOne[iLength-i] * pdArrayTwo[i];

            pdArrayOne[i] = dReal;
            pdArrayOne[iLength-i] = dImag;
          }
        }

        //
        // do the inverse FFT...
        //
        if (gsl_fft_halfcomplex_radix2_inverse( pdArrayOne, 1, iLength ) == 0) {
          if (step_value->length() != array_one->length()) {
            pdResult[0] = (double*)realloc( step_value->value(), array_one->length() * sizeof( double ) );
          } else {
            pdResult[0] = step_value->value();
          }

          if (correlated->length() != array_two->length()) {
            pdResult[1] = (double*)realloc( correlated->value(), array_two->length() * sizeof( double ) );
          } else {
            pdResult[1] = correlated->value();
          }

          if (pdResult[0] != NULL && pdResult[1] != NULL) {
            for (int i = 0; i < array_one->length(); ++i) {
              step_value->value()[i] = pdResult[0][i];
            }
            for (int i = 0; i < array_two->length(); ++i) {
              correlated->value()[i] = pdResult[1][i];
            }

            for (int i = 0; i < array_one->length(); i++) {
                step_value->value()[i] = (double)( i - ( array_one->length() / 2 ) );
            }

            memcpy( &(correlated->value()[array_one->length() / 2]),
                    &(pdArrayOne[0]),
                    ( ( array_one->length() + 1 ) / 2 ) * sizeof( double ) );

            memcpy( &(correlated->value()[0]),
                    &(pdArrayOne[iLength - (array_one->length() / 2)]),
                    ( array_one->length() / 2 ) * sizeof( double ) );

            iReturn = true;
          }
        }
      }
    }
  }
  delete[] pdArrayOne;
  delete[] pdArrayTwo;

  return iReturn;
}
Example #17
0
void doTests() {

  KstVectorPtr vp = new KstVector(KstObjectTag("tempVector"), 10);
  for (int i = 0; i < 10; i++){
    vp->value()[i] = i;
  }

  KstPSDPtr psd = new KstPSD(QString("psdTest"), vp, 0.0, false, 10, false, false, QString("vUnits"), QString("rUnits"), WindowUndefined, 0.0, PSDUndefined);
  doTest(psd->tagName() == "psdTest");
  doTest(psd->vTag() == "tempVector");
  doTest(psd->output() == PSDUndefined);
  doTest(!psd->apodize());
  doTest(!psd->removeMean());
  doTest(!psd->average());
  doTest(psd->freq() == 0.0);
  doTest(psd->apodizeFxn() == WindowUndefined);
  doTest(psd->gaussianSigma() == 0);
  KstVectorPtr vpVX = psd->vX();
  KstVectorPtr vpVY = psd->vY();

  // until we call update the x and y vectors will be uninitialised and
  // and so they should be of length 1 and the value of vpVX[0] and 
  // vpVX[0] should be NAN...
  doTestV(QString("vpVX->length()"), vpVX->length(), 1);
  doTestV(QString("vpVY->length()"), vpVY->length(), 1);
  doTestV(QString("vpVX->length()"), isnan(vpVX->value()[0]), 1);
  doTestV(QString("vpVY->length()"), isnan(vpVY->value()[0]), 1);

  doTest(psd->update(0) == KstObject::UPDATE);

  for(int j = 0; j < vpVX->length(); j++){
      doTest(vpVX->value()[j] == 0);
  }

  psd->setOutput(PSDAmplitudeSpectralDensity);
  psd->setApodize(true);
  psd->setRemoveMean(true);
  psd->setAverage(true);
  psd->setFreq(0.1);
  psd->setApodizeFxn(WindowOriginal);
  psd->setGaussianSigma(0.2);

  doTest(psd->tagName() == "psdTest");
  doTest(psd->vTag() == "tempVector");
  doTest(psd->output() == PSDAmplitudeSpectralDensity);
  doTest(psd->apodize());
  doTest(psd->removeMean());
  doTest(psd->average());
  doTest(psd->freq() == 0.1);
  doTest(psd->apodizeFxn() == WindowOriginal);
  doTest(psd->gaussianSigma() == 0.2);
  
//   doTest(psd->update(0) == KstObject::UPDATE);
//   QString ps = "PSD: " + psd->vTag();
//   doTest(psd->propertyString() == ps);
//    doTest(!psd->curveHints().curveName() == "");
//   printf("Curve name [%s]", kstCHL[0].curveName());
//   printf("X Vector name [%s]", kstCHL[0].xVectorName());
//   printf("Y Vector name [%s]", kstCHL[0].yVectorName());

  KTempFile tf(locateLocal("tmp", "kst-csd"), "txt");
  QFile *qf = tf.file();
  QTextStream ts(qf);
  psd->save(ts, "");
  QFile::remove(tf.name());

  QDomNode n = makeDOMElement("psdDOMPsd", "psdDOMVector").firstChild();
  QDomElement e = n.toElement();
  KstPSDPtr psdDOM = new KstPSD(e);

  doTest(psdDOM->tagName() == "psdDOMPsd");
  doTest(psdDOM->output() == PSDAmplitudeSpectralDensity);
  doTest(psdDOM->apodize());
  doTest(psdDOM->removeMean());
  doTest(psdDOM->average());
  doTest(psdDOM->freq() == 128);
  doTest(psdDOM->apodizeFxn() == WindowOriginal);
  doTest(psdDOM->gaussianSigma() == 0.01);

//   KstVectorPtr vpVX = psdDOM->vX();
//   for(int j = 0; j < vpVX->length(); j++){
//       printf("[%d][%lf]", j, vpVX->value()[j]);
//   }
//   KstVectorPtr vpVY = psdDOM->vY();
}
Example #18
0
bool Statistics::algorithm() {

  KstVectorPtr data               = inputVector(DATA);
  KstScalarPtr mean               = outputScalar(MEAN);
  KstScalarPtr minimum            = outputScalar(MINIMUM);
  KstScalarPtr maximum            = outputScalar(MAXIMUM);
  KstScalarPtr variance           = outputScalar(VARIANCE);
  KstScalarPtr standard_deviation = outputScalar(STANDARD_DEVIATION);
  KstScalarPtr median             = outputScalar(MEDIAN);
  KstScalarPtr absolute_deviation = outputScalar(ABSOLUTE_DEVIATION);
  KstScalarPtr skewness           = outputScalar(SKEWNESS);
  KstScalarPtr kurtosis           = outputScalar(KURTOSIS);

  double* pCopy;
  double dMean = 0.0;
  double dMedian = 0.0;
  double dStandardDeviation = 0.0;
  double dTotal = 0.0;
  double dSquaredTotal = 0.0;
  double dMinimum = 0.0;
  double dMaximum = 0.0;
  double dVariance = 0.0;
  double dAbsoluteDeviation = 0.0;
  double dSkewness = 0.0;
  double dKurtosis = 0.0;
  int iLength;
  int iRetVal = false;

  if (data->length() > 0) {
    iLength = data->length();

    for (int i=0; i<iLength; i++) {
      if (i == 0 || data->value()[i] < dMinimum) {
        dMinimum = data->value()[i];
      }
      if (i == 0 || data->value()[i] > dMaximum) {
        dMaximum = data->value()[i];
      }
      dTotal += data->value()[i];
      dSquaredTotal += data->value()[i] * data->value()[i];
    }

    dMean = dTotal / (double)iLength;
    if (iLength > 1) {
      dVariance  = 1.0 / ( (double)iLength - 1.0 );
      dVariance *= dSquaredTotal - ( dTotal * dTotal / (double)iLength ); 
      if (dVariance > 0.0) {
        dStandardDeviation = sqrt( dVariance );
      } else {
        dVariance = 0.0;
        dStandardDeviation = 0.0;
      }
    }

    for (int i=0; i<iLength; i++) {
      dAbsoluteDeviation += fabs( data->value()[i] - dMean );
      dSkewness               += pow( data->value()[i] - dMean, 3.0 );
      dKurtosis               += pow( data->value()[i] - dMean, 4.0 );
    }
    dAbsoluteDeviation /= (double)iLength;
    dSkewness                 /= (double)iLength * pow( dStandardDeviation, 3.0 );
    dKurtosis                 /= (double)iLength * pow( dStandardDeviation, 4.0 );
    dKurtosis                 -= 3.0;

    /*
    sort by phase...
    */
    pCopy = (double*)calloc( iLength, sizeof( double ) );
    if (pCopy != NULL) {
      memcpy( pCopy, data->value(), iLength * sizeof( double ) );
      quicksort( pCopy, 0, iLength-1 );
      dMedian = pCopy[ iLength / 2 ];

      free( pCopy );
    }

    mean->setValue(dMean);
    minimum->setValue(dMinimum);
    maximum->setValue(dMaximum);
    variance->setValue(dVariance);
    standard_deviation->setValue(dStandardDeviation);
    median->setValue(dMedian);
    absolute_deviation->setValue(dAbsoluteDeviation);
    skewness->setValue(dSkewness);
    kurtosis->setValue(dKurtosis);

    iRetVal = true;
  }

  return iRetVal;
}
Example #19
0
void KstViewFitsDialog::fitChanged(const QString& strFit) {
  KstCPluginList fits;
  KstCPluginPtr plugin;
  double* params = 0L;
  double* covars = 0L;
  double chi2Nu = 0.0;
  int numParams = 0;
  int numCovars = 0;
  int i;

  fits = kstObjectSubList<KstDataObject,KstCPlugin>(KST::dataObjectList);
  plugin = *(fits.findTag(strFit));
  if (plugin) {
    KstScalarPtr scalarChi2Nu;
    KstVectorPtr vectorParam;
    plugin->readLock();

    const KstScalarMap& scalars = plugin->outputScalars();
    
    scalarChi2Nu = scalars["chi^2/nu"];
    if (scalarChi2Nu) {
      scalarChi2Nu->readLock();
      chi2Nu = scalarChi2Nu->value();
      scalarChi2Nu->unlock();
    }

    const KstVectorMap& vectors = plugin->outputVectors();
    vectorParam = vectors["Parameters"];

    if (vectorParam) {
      KstVectorPtr vectorCovar;

      vectorParam->readLock();
      vectorCovar = vectors["Covariance"];
      if (vectorCovar) {
        vectorCovar->readLock();
        numParams = vectorParam->length();
        numCovars = vectorCovar->length();

        if (numParams > 0 && numCovars > 0) {
          params = new double[numParams];
          covars = new double[numCovars];

          for (i = 0; i < numParams; i++) {
            params[i] = vectorParam->value(i);
          }

          for (i = 0; i < numCovars; i++) {
            covars[i] = vectorCovar->value(i);
          }
        }
        vectorCovar->unlock();
      }
      vectorParam->unlock();
    }
    plugin->unlock();
  }

  _tableFits->setParameters(params, numParams, covars, numCovars, chi2Nu);

  if (numParams > 0) {
    _tableFits->horizontalHeaderItem(0)->setText(QObject::tr("Value"));
    _tableFits->horizontalHeaderItem(1)->setText(QObject::tr("Covariance:"));

    _tableFits->verticalHeaderItem(numParams+0)->setText("---");
    _tableFits->verticalHeaderItem(numParams+1)->setText(QObject::tr("Chi^2/Nu"));

    if (plugin) {
      QExplicitlySharedDataPointer<Plugin> pluginBase;

      plugin->readLock();
      pluginBase = plugin->plugin();

      if (pluginBase) {
        textLabelFit->setText(pluginBase->data()._readableName);
        for (i = 0; i < numParams; i++) {
          QString parameterName = pluginBase->parameterName(i);
          _tableFits->horizontalHeaderItem(i+2)->setText(parameterName);
          _tableFits->verticalHeaderItem(i)->setText(parameterName);
        }
      }
      plugin->unlock();
    }
  }

  _tableFits->update();
}
Example #20
0
KstObject::UpdateType KstCSD::update(int update_counter) {

  KstVectorPtr inVector = _inputVectors[INVECTOR];

  bool force = dirty();
  setDirty(false);

  if (KstObject::checkUpdateCounter(update_counter) && !force) {
    return lastUpdateResult();
  }

  if (update_counter <= 0) {
    assert(update_counter == 0);
    force = true;
  }

  bool xUpdated = KstObject::UPDATE == inVector->update(update_counter);
  // if vector was not changed, don't update the CSD
  if (!xUpdated && !force) {
    return setLastUpdateResult(NO_CHANGE);
  }

  double *tempOutput, *input;
  int tempOutputLen = PSDCalculator::calculateOutputVectorLength(_windowSize, _average, _averageLength);
  _PSDLen = tempOutputLen;
  tempOutput = new double[tempOutputLen];

  input = inVector->value();

  int xSize = 0;
  for (int i=0; i < inVector->length(); i+= _windowSize) {
    //ensure there is enough data left.
    if (i + _windowSize >= inVector->length()) {
        break; //If there isn't enough left for a complete window.
    }

    _psdCalculator.calculatePowerSpectrum(input + i, _windowSize, tempOutput, tempOutputLen, _removeMean,  false, _average, _averageLength, _apodize, _apodizeFxn, _gaussianSigma, _outputType, _frequency);
    
    // resize output matrix
    (*_outMatrix)->resize(xSize+1, tempOutputLen);

    if ((*_outMatrix)->sampleCount() == (xSize+1)*tempOutputLen) { // all is well.
      // copy elements to output matrix
      for (int j=0; j < tempOutputLen; j++) {
        (*_outMatrix)->setValueRaw(xSize, j, tempOutput[j]);
      }
    } else {
      KstDebug::self()->log(i18n("Could not allocate sufficient memory for CSD."), KstDebug::Error);
      break;
    }

    xSize++;
  }

  delete tempOutput;

  double frequencyStep = .5*_frequency/(double)(tempOutputLen-1);

  (*_outMatrix)->change((*_outMatrix)->tagName(), xSize, tempOutputLen, 0, 0, _windowSize, frequencyStep);
  (*_outMatrix)->update(update_counter);

  return setLastUpdateResult(UPDATE);
}
Example #21
0
KstObject::UpdateType KstCSD::update(int update_counter) {
  
  KstVectorPtr inVector = _inputVectors[INVECTOR];

  bool force = dirty();
  setDirty(false);

  if (KstObject::checkUpdateCounter(update_counter) && !force) {
    return lastUpdateResult();
  }

  if (update_counter <= 0) {
    assert(update_counter == 0);
    force = true;
  }

  bool xUpdated = KstObject::UPDATE == inVector->update(update_counter);
  // if vector was not changed, don't update the CSD
  if ((!xUpdated) && !force ) {
    return setLastUpdateResult(NO_CHANGE);
  }
  
  // create a psd generator
  KstPSDGenerator psdGenerator(0L, _frequency, _average, _length,
                               _apodize, _removeMean, _apodizeFxn, _gaussianSigma);
  int xSize = 0;
  for (int i=0; i < inVector->length(); i+= _windowSize + 1) {
    int vectorSize = _windowSize;
    // determine size of actual input data
    if (i + _windowSize >= inVector->length()) {
      if (i == 0) {
        // if this is the one and only window, get a PSD
        vectorSize = i + _windowSize - inVector->length();
      } else {
        // don't PSD the last window if it is chopped off
        break;  
      }
    }
    
    // copy input vector elements into subvector
    QValueVector<double> psdInputVector(_windowSize, 0);
    double* inVectorArray = inVector->value();
    for (int j=0; j < vectorSize; j++) {
      psdInputVector[j] = inVectorArray[i+j];
    }

    // set the vector and calculate PSD
    psdGenerator.setInputVector(&psdInputVector);
    psdGenerator.updateNow();
    
    // resize output matrix
    (*_outMatrix)->resize(xSize+1, psdGenerator.powerVector()->size());
    
    // copy elements to output matrix
    for (uint j=0; j < psdGenerator.powerVector()->size(); j++) {
      (*_outMatrix)->setValueRaw(xSize, j, psdGenerator.powerVector()->at(j));
    }
    xSize++;
  }
 
  (*_outMatrix)->change((*_outMatrix)->tagName(), xSize, psdGenerator.frequencyVector()->size(), 0, 0, _windowSize, psdGenerator.frequencyVectorStep());
  
  (*_outMatrix)->update(update_counter);
      
  return setLastUpdateResult(UPDATE);
}
Example #22
0
bool AutoCorrelate::algorithm() {

  KstVectorPtr array            = inputVector(ARRAY);
  KstVectorPtr step_value       = outputVector(STEP_VALUE);
  KstVectorPtr auto_correlated  = outputVector(AUTO_CORRELATED);

  if (array->length() <= 0) {
    return false;
  }

  double* pdArrayOne;
  double* pdResult;
  double* pdCorrelate;
  double  dReal;
  double  dImag;
  double  sigmaSquared = 0.0;

  int iLength;
  int iLengthNew;

  bool iReturn = false;

  //
  // zero-pad the array...
  //
  iLength  = array->length();
  iLength *= 2;

  step_value->resize(array->length(), false);
  auto_correlated->resize(array->length(), false);

  //
  // round iLength up to the nearest power of two...
  //
  iLengthNew = 64;
  while( iLengthNew < iLength && iLengthNew > 0) {
    iLengthNew *= 2;
  }
  iLength = iLengthNew;

  if (iLength <= 0) {
    return false;
  }

  pdArrayOne = new double[iLength];
  if (pdArrayOne != NULL) {
    //
    // zero-pad the two arrays...
    //
    memset( pdArrayOne, 0, iLength * sizeof( double ) );
    memcpy( pdArrayOne, array->value(), array->length() * sizeof( double ) );

    //
    // calculate the FFTs of the two functions...
    //
    if (gsl_fft_real_radix2_transform( pdArrayOne, 1, iLength ) == 0) {
      //
      // multiply the FFT by its complex conjugate...
      //
      for (int i=0; i<iLength/2; i++) {
        if (i==0 || i==(iLength/2)-1) {
          pdArrayOne[i] *= pdArrayOne[i];
        } else {
          dReal = pdArrayOne[i] * pdArrayOne[i] + pdArrayOne[iLength-i] * pdArrayOne[iLength-i];
          dImag = pdArrayOne[i] * pdArrayOne[iLength-i] - pdArrayOne[iLength-i] * pdArrayOne[i];

          pdArrayOne[i] = dReal;
          pdArrayOne[iLength-i] = dImag;
        }
      }

      //
      // do the inverse FFT...
      //
      if (gsl_fft_halfcomplex_radix2_inverse( pdArrayOne, 1, iLength ) == 0) {
        if (step_value->length() != array->length()) {
          pdResult = (double*)realloc( step_value->value(), array->length() * sizeof( double ) );
        } else {
          pdResult = step_value->value();
        }

        if (auto_correlated->length() != array->length()) {
          pdCorrelate = (double*)realloc( auto_correlated->value(), array->length() * sizeof( double ) );
        } else {
          pdCorrelate = auto_correlated->value();
        }

        if (pdResult != NULL && pdCorrelate != NULL) {
          sigmaSquared = pdArrayOne[0];

          memcpy( &(auto_correlated->value()[array->length() / 2]),
                  &(pdArrayOne[0]),
                  ( ( array->length() + 1 ) / 2 ) * sizeof( double ) );

          memcpy( &(auto_correlated->value()[0]),
                  &(pdArrayOne[iLength - (array->length() / 2)]),
                  ( array->length() / 2 ) * sizeof( double ) );

          for (int i = 0; i < array->length(); i++) {
            auto_correlated->value()[i] /= sigmaSquared;
            step_value->value()[i] = (double)( i - ( array->length() / 2 ) );
          }

          iReturn = true;
        }
      }
    }
  }
  delete[] pdArrayOne;

  return iReturn;
}
Example #23
0
KstObject::UpdateType EventMonitorEntry::update(int updateCounter) {
  Q_ASSERT(myLockStatus() == KstRWLock::WRITELOCKED);

  bool force = dirty();
  setDirty(false);

  if (KstObject::checkUpdateCounter(updateCounter) && !force) {
    return lastUpdateResult();
  }

  writeLockInputsAndOutputs();

  if (!_pExpression) {
    reparse();
  }

  KstVectorPtr xv = *_xVector;
  KstVectorPtr yv = *_yVector;
  int ns = 1;

  for (KstVectorMap::ConstIterator i = _vectorsUsed.begin(); i != _vectorsUsed.end(); ++i) {
    ns = qMax(ns, i.value()->length());
  }

  double *rawValuesX = 0L;
  double *rawValuesY = 0L;
  if (xv && yv) {
    if (xv->resize(ns)) {
      rawValuesX = xv->value();
    }

    if (yv->resize(ns)) {
      rawValuesY = yv->value();
    }
  }

  Equation::Context ctx;
  ctx.sampleCount = ns;
  ctx.x = 0.0;

  if (needToEvaluate()) {
    if (_pExpression) {
      for (ctx.i = _numDone; ctx.i < ns; ++ctx.i) {
        const double value = _pExpression->value(&ctx);
        if (value != 0.0) { // The expression evaluates to true
          log(ctx.i);
          if (rawValuesX && rawValuesY) {
            rawValuesX[ctx.i] = ctx.i;
            rawValuesY[ctx.i] = 1.0;
          }
        } else {
          if (rawValuesX && rawValuesY) {
            rawValuesX[ctx.i] = ctx.i;
            rawValuesY[ctx.i] = 0.0;
          }
        }
      }
      _numDone = ns;
      logImmediately();
    }
  } else {
    _numDone = ns;
  }

  if (xv) {
    xv->setDirty();
    xv->update(updateCounter);
  }

  if (yv) {
    yv->setDirty();
    yv->update(updateCounter);
  }

  unlockInputsAndOutputs();

  return setLastUpdateResult(NO_CHANGE);
}
void KstViewLabel::DataCache::update() {
  for (QValueVector<DataRef>::ConstIterator i = data.begin(); valid && i != data.end(); ++i) {
    switch ((*i).type) {
      case DataRef::DataRef::DRScalar:
        {
          KST::scalarList.lock().readLock();
          KstScalarPtr p = *KST::scalarList.findTag((*i).name);
          KST::scalarList.lock().unlock();
          if (p) {
            p->readLock();
            if (QVariant(p->value()) != (*i).value) {
              valid = false;
            }
            p->unlock();
          }
        }
        break;

      case DataRef::DRString:
        {
          KST::stringList.lock().readLock();
          KstStringPtr p = *KST::stringList.findTag((*i).name);
          KST::stringList.lock().unlock();
          if (p) {
            p->readLock();
            if (QVariant(p->value()) != (*i).value) {
              valid = false;
            }
            p->unlock();
          }
        }
        break;

      case DataRef::DRExpression:
        {
          bool ok = false;
          const double val = Equation::interpret((*i).name.latin1(), &ok, (*i).name.length());
          if (QVariant(val) != (*i).value) {
            valid = false;
          }
        }
        break;

      case DataRef::DRVector:
        {
          bool ok = false;
          const double idx = Equation::interpret((*i).index.latin1(), &ok, (*i).index.length());
          if (idx != (*i).indexValue) {
            valid = false;
            break;
          }
          KST::vectorList.lock().readLock();
          KstVectorPtr p = *KST::vectorList.findTag((*i).name);
          KST::vectorList.lock().unlock();
          if (p) {
            p->readLock();
            if (QVariant(p->value(int((*i).indexValue))) != (*i).value) {
              valid = false;
            }
            p->unlock();
          }
        }
        break;

      case DataRef::DataRef::DRFit:
        {
          KST::dataObjectList.lock().readLock();
          KstDataObjectList::Iterator oi = KST::dataObjectList.findTag((*i).name);
          KST::dataObjectList.lock().unlock();
          if (oi != KST::dataObjectList.end()) {
            KstCPluginPtr fit = kst_cast<KstCPlugin>(*oi);
            if (fit) {
              fit->readLock(); 
              if (fit->label((int)((*i).indexValue)) != (*i).index) {
                valid = false;
              }
              fit->unlock();
            }
          }
        }
        break;
    }
  }
}
KstObject::UpdateType KstCPlugin::update(int update_counter) {
  Q_ASSERT(myLockStatus() == KstRWLock::WRITELOCKED);

  if (!isValid()) {
    return setLastUpdateResult(NO_CHANGE);
  }

  if (recursed()) {
    return setLastUpdateResult(NO_CHANGE);
  }

  bool force = dirty();
  setDirty(false);

  if (KstObject::checkUpdateCounter(update_counter) && !force) {
    return lastUpdateResult();
  }

#define CLEANUP() do {\
  for (unsigned i = 0; i < _outStringCnt; ++i) { \
    if (_outStrings[i]) { \
      free(_outStrings[i]); \
      _outStrings[i] = 0L; \
    } \
  } \
  for (unsigned i = 0; i < _inStringCnt; ++i) { \
    if (_inStrings[i]) { \
      free(_inStrings[i]); \
      _inStrings[i] = 0L; \
    } \
  } \
  } while(0)


  writeLockInputsAndOutputs();

  const QValueList<Plugin::Data::IOValue>& itable = _plugin->data()._inputs;
  const QValueList<Plugin::Data::IOValue>& otable = _plugin->data()._outputs;
  int itcnt = 0, vitcnt = 0, sitcnt = 0;
  bool doUpdate = force;

  // Populate the input scalars and vectors
  for (QValueList<Plugin::Data::IOValue>::ConstIterator it = itable.begin(); it != itable.end(); ++it) {
    if ((*it)._type == Plugin::Data::IOValue::TableType) {
      if (!_inputVectors.contains((*it)._name)) {
        KstDebug::self()->log(i18n("Input vector [%1] for plugin %2 not found.  Unable to continue.").arg((*it)._name).arg(tagName()), KstDebug::Error);
        CLEANUP();
        return setLastUpdateResult(NO_CHANGE);
      }
      KstVectorPtr iv = _inputVectors[(*it)._name];
      if (!iv) {
        kstdFatal() << "Input vector \"" << (*it)._name << "\" for plugin " << tag().displayString() << " is invalid." << endl;
      }
      doUpdate = (UPDATE == iv->update(update_counter)) || doUpdate;
      _inVectors[vitcnt] = iv->value();
      _inArrayLens[vitcnt++] = iv->length();
    } else if ((*it)._type == Plugin::Data::IOValue::FloatType) {
      KstScalarPtr is = _inputScalars[(*it)._name];
      if (!is) {
        kstdFatal() << "Input scalar \"" << (*it)._name << "\" for plugin " << tag().displayString() << " is invalid." << endl;
      }
      doUpdate = (UPDATE == is->update(update_counter)) || doUpdate;
      _inScalars[itcnt++] = is->value();
    } else if ((*it)._type == Plugin::Data::IOValue::StringType) {
      KstStringPtr is = _inputStrings[(*it)._name];
      if (!is) {
        kstdFatal() << "Input string \"" << (*it)._name << "\" for plugin " << tag().displayString() << " is invalid." << endl;
      }
      doUpdate = (UPDATE == is->update(update_counter)) || doUpdate;
      // Maybe we should use UTF-8 instead?
      _inStrings[sitcnt++] = strdup(is->value().latin1());
    } else if ((*it)._type == Plugin::Data::IOValue::PidType) {
      _inScalars[itcnt++] = getpid();
    }
  }

  if (!doUpdate) {
    CLEANUP();
    unlockInputsAndOutputs();
    return setLastUpdateResult(NO_CHANGE);
  }

  vitcnt = 0;
  // Populate the output vectors
  for (QValueList<Plugin::Data::IOValue>::ConstIterator it = otable.begin();
                                                         it != otable.end();
                                                                        ++it) {
    if ((*it)._type == Plugin::Data::IOValue::TableType) {
      if (!_outputVectors.contains((*it)._name)) {
        KstDebug::self()->log(i18n("Output vector [%1] for plugin %2 not found.  Unable to continue.").arg((*it)._name).arg(tagName()), KstDebug::Error);
        CLEANUP();
        unlockInputsAndOutputs();
        return setLastUpdateResult(NO_CHANGE);
      }
      _outVectors[vitcnt] = _outputVectors[(*it)._name]->value();
      _outArrayLens[vitcnt++] = _outputVectors[(*it)._name]->length();
    }
  }

  if (_outStringCnt > 0) {
    memset(_outStrings, 0, _outStringCnt*sizeof(char *));
  }

  int rc;
  if (_inStringCnt > 0 || _outStringCnt > 0) {
    if (_plugin->data()._localdata) {
      rc = _plugin->call(_inVectors, _inArrayLens, _inScalars,
          _outVectors, _outArrayLens, _outScalars,
          const_cast<const char**>(_inStrings), _outStrings, &_localData);
    } else {
      rc = _plugin->call(_inVectors, _inArrayLens, _inScalars,
          _outVectors, _outArrayLens, _outScalars,
          const_cast<const char**>(_inStrings), _outStrings);
    }
  } else {
    if (_plugin->data()._localdata) {
      rc = _plugin->call(_inVectors, _inArrayLens, _inScalars,
          _outVectors, _outArrayLens, _outScalars, &_localData);
    } else {
      rc = _plugin->call(_inVectors, _inArrayLens, _inScalars,
          _outVectors, _outArrayLens, _outScalars);
    }
  }

  if (rc == 0) {
    itcnt = 0;
    vitcnt = 0;
    sitcnt = 0;
    setLastUpdateResult(UPDATE); // make sure that provider callbacks work
    // Read back the output vectors and scalars
    for (QValueList<Plugin::Data::IOValue>::ConstIterator it = otable.begin();
        it != otable.end();
        ++it) {
      if ((*it)._type == Plugin::Data::IOValue::TableType) {
        KstVectorPtr vp = _outputVectors[(*it)._name];
        vectorRealloced(vp, _outVectors[vitcnt], _outArrayLens[vitcnt]);
        vp->setDirty();
        // Inefficient, but do we have any other choice?  We don't really know
        // from the plugin how much of this vector is "new" or "shifted"
        vp->setNewAndShift(vp->length(), vp->numShift());
        vp->update(update_counter);
        vitcnt++;
      } else if ((*it)._type == Plugin::Data::IOValue::FloatType) {
        KstScalarPtr sp = _outputScalars[(*it)._name];
        sp->setValue(_outScalars[itcnt++]);
        sp->update(update_counter);
      } else if ((*it)._type == Plugin::Data::IOValue::StringType) {
        KstStringPtr sp = _outputStrings[(*it)._name];
        sp->setValue(_outStrings[sitcnt++]);
        sp->update(update_counter);
      }
    }

    // if we have a fit plugin then create the necessary scalars from the parameter vector
    createFitScalars();
    _lastError = QString::null;
  } else if (rc > 0) {
    if (_lastError.isEmpty()) {
      const char *err = _plugin->errorCode(rc);
      if (err && *err) {
        _lastError = err;
        KstDebug::self()->log(i18n("Plugin %1 produced error: %2.").arg(tagName()).arg(_lastError), KstDebug::Error);
      } else {
        _lastError = QString::null;
      }
    }
  } else {
    bool doSend = _lastError.isEmpty() ? true : false;

    switch (rc) {
      case -1:
        _lastError = i18n("Generic Error");
        break;
      case -2:
        _lastError = i18n("Input Error");
        break;
      case -3:
        _lastError = i18n("Memory Error");
        break;
      default:
        _lastError = i18n("Unknown Error");
        break;
    }

    if (doSend) {
      KstDebug::self()->log(i18n("Plugin %2 produced error: %1.").arg(_lastError).arg(tagName()), KstDebug::Error);
    }
  }

  unlockInputsAndOutputs();

  CLEANUP();
#undef CLEANUP
  return setLastUpdateResult(UPDATE);
}
void CrossPowerSpectrum::crossspectrum() {
  KstVectorPtr v1 = *_inputVectors.find(VECTOR_ONE);
  KstVectorPtr v2 = *_inputVectors.find(VECTOR_TWO);

  KstScalarPtr fft = *_inputScalars.find(FFT_LENGTH);
  KstScalarPtr sample = *_inputScalars.find(SAMPLE_RATE);

  KstVectorPtr real = *_outputVectors.find(REAL);
  KstVectorPtr imaginary = *_outputVectors.find(IMAGINARY);
  KstVectorPtr frequency = *_outputVectors.find(FREQUENCY);

  double SR = sample->value(); // sample rate
  double df;
  int i,  xps_len;
  double *a,  *b;
  double mean_a,  mean_b;
  int dv0,  dv1,  v_len;
  int i_subset,  n_subsets;
  int i_samp,  copyLen;
  double norm_factor;

  /* parse fft length */
  xps_len = int( fft->value() - 0.99);
  if ( xps_len > KSTPSDMAXLEN ) xps_len = KSTPSDMAXLEN;
  if ( xps_len<2 ) xps_len = 2;
  xps_len = int ( pow( 2,  xps_len ) );

  /* input vector lengths */
  v_len = ( ( v1->length() < v2->length() ) ?
            v1->length() : v2->length() );
  dv0 = v_len/v1->length();
  dv1 = v_len/v2->length();

  while ( xps_len > v_len ) xps_len/=2;

  // allocate the lengths
  if ( real->length() != xps_len ) {
    real->resize( xps_len, false );
    imaginary->resize( xps_len, false );
    frequency->resize( xps_len, false );
  }

  /* Fill the frequency and zero the xps */
  df = SR/( 2.0*double( xps_len-1 ) );
  for ( i=0; i<xps_len; i++ ) {
    frequency->value()[i] = double( i ) * df;
    real->value()[i] = 0.0;
    imaginary->value()[i] = 0.0;
  }

  /* allocate input arrays */
  int ALen = xps_len * 2;
  a = new double[ALen];
  b = new double[ALen];

  /* do the fft's */
  n_subsets = v_len/xps_len + 1;

  for ( i_subset=0; i_subset<n_subsets; i_subset++ ) {
        /* copy each chunk into a[] and find mean */
    if (i_subset*xps_len + ALen <= v_len) {
      copyLen = ALen;
    } else {
      copyLen = v_len - i_subset*xps_len;
    }
    mean_b = mean_a = 0;
    for (i_samp = 0; i_samp < copyLen; i_samp++) {
      i = ( i_samp + i_subset*xps_len )/dv0;
      mean_a += (
        a[i_samp] = v1->value()[i]
        );
      i = ( i_samp + i_subset*xps_len )/dv1;
      mean_b += (
        b[i_samp] = v2->value()[i]
        );
    }
    if (copyLen>1) {
      mean_a/=(double)copyLen;
      mean_b/=(double)copyLen;
    }

    /* Remove Mean and apodize */
    for (i_samp=0; i_samp<copyLen; i_samp++) {
      a[i_samp] -= mean_a;
      b[i_samp] -= mean_b;
    }

    for (;i_samp < ALen; i_samp++) {
      a[i_samp] = 0.0;
      b[i_samp] = 0.0;
    }

    /* fft */
    rdft(ALen, 1, a);
    rdft(ALen, 1, b);

    /* sum each bin into psd[] */
    real->value()[0] += ( a[0]*b[0] );
    real->value()[xps_len-1] += ( a[1]*b[1] );
    for (i_samp=1; i_samp<xps_len-1; i_samp++) {
      real->value()[i_samp]+= ( a[i_samp*2] * b[i_samp*2] +
                                   a[i_samp*2+1] * b[i_samp*2+1] );
      imaginary->value()[i_samp]+= ( -a[i_samp*2] * b[i_samp*2+1] +
                                   a[i_samp*2+1] * b[i_samp*2] );
    }// (a+ci)(b+di)* = ab+cd +i(-ad + cb)
  }

  /* renormalize */
  norm_factor = 1.0/((double(SR)*double(xps_len))*double(n_subsets));
  for ( i=0; i<xps_len; i++ ) {
    real->value()[i]*=norm_factor;
    imaginary->value()[i]*=norm_factor;
  }

  /* free */
  delete[] b;
  delete[] a;
//   return 0;
}
Example #27
0
bool KstEquation::FillY(bool force) {
  int v_shift=0, v_new;
  int i0=0;
  int ns;

  writeLockInputsAndOutputs();

  // determine value of Interp
  if (_doInterp) {
    ns = (*_xInVector)->length();
    for (KstVectorMap::ConstIterator i = VectorsUsed.begin(); i != VectorsUsed.end(); ++i) {
      if (i.data()->length() > ns) {
        ns = i.data()->length();
      }
    }
  } else {
    ns = (*_xInVector)->length();
  }

  if (_ns != (*_xInVector)->length() || ns != (*_xInVector)->length() ||
      (*_xInVector)->numShift() != (*_xInVector)->numNew()) {
    _ns = ns;

    KstVectorPtr xv = *_xOutVector;
    KstVectorPtr yv = *_yOutVector;
    if (!xv->resize(_ns)) {
      // FIXME: handle error?
      unlockInputsAndOutputs();
      return false;    
    }
    if (!yv->resize(_ns)) {
      // FIXME: handle error?
      unlockInputsAndOutputs();
      return false;
    }
    yv->zero();
    i0 = 0; // other vectors may have diffent lengths, so start over
    v_shift = _ns;
  } else {
    // calculate shift and new samples
    // only do shift optimization if all used vectors are same size and shift
    v_shift = (*_xInVector)->numShift();
    v_new = (*_xInVector)->numNew();

    for (KstVectorMap::ConstIterator i = VectorsUsed.begin(); i != VectorsUsed.end(); ++i) {
      if (v_shift != i.data()->numShift()) {
        v_shift = _ns;
      }
      if (v_new != i.data()->numNew()) {
        v_shift = _ns;
      }
      if (_ns != i.data()->length()) {
        v_shift = _ns;
      }
    }

    if (v_shift > _ns/2 || force) {
      i0 = 0;
      v_shift = _ns;
    } else {
      KstVectorPtr xv = *_xOutVector;
      KstVectorPtr yv = *_yOutVector;
      for (int i = v_shift; i < _ns; i++) {
        yv->value()[i - v_shift] = yv->value()[i];
        xv->value()[i - v_shift] = xv->value()[i];
      }
      i0 = _ns - v_shift;
    }
  }

  _numShifted = (*_yOutVector)->numShift() + v_shift;
  if (_numShifted > _ns) {
    _numShifted = _ns;
  }

  _numNew = _ns - i0 + (*_yOutVector)->numNew();
  if (_numNew > _ns) {
    _numNew = _ns;
  }

  (*_xOutVector)->setNewAndShift(_numNew, _numShifted);
  (*_yOutVector)->setNewAndShift(_numNew, _numShifted);

  double *rawxv = (*_xOutVector)->value();
  double *rawyv = (*_yOutVector)->value();
  KstVectorPtr iv = (*_xInVector);

  Equation::Context ctx;
  ctx.sampleCount = _ns;
  ctx.xVector = iv;

  if (!_pe) {
    if (_equation.isEmpty()) {
      unlockInputsAndOutputs();
      return true;
    }

    QMutexLocker ml(&Equation::mutex());
    yy_scan_string(_equation.latin1());
    int rc = yyparse();
    _pe = static_cast<Equation::Node*>(ParsedEquation);
    if (_pe && rc == 0) {
      Equation::FoldVisitor vis(&ctx, &_pe);
      KstStringMap sm;
      _pe->collectObjects(VectorsUsed, ScalarsUsed, sm);
      ParsedEquation = 0L;
    } else {
      delete (Equation::Node*)ParsedEquation;
      ParsedEquation = 0L;
      _pe = 0L;
      unlockInputsAndOutputs();
      return false;
    }
  }

  for (ctx.i = i0; ctx.i < _ns; ++ctx.i) {
    rawxv[ctx.i] = iv->value(ctx.i);
    ctx.x = iv->interpolate(ctx.i, _ns);
    rawyv[ctx.i] = _pe->value(&ctx);
  }

  if (!(*_xOutVector)->resize(iv->length())) {
    // FIXME: handle error?
    unlockInputsAndOutputs();
    return false;    
  }

  unlockInputsAndOutputs();
  return true;
}
KstObject::UpdateType KstPSD::update(int update_counter) {
  Q_ASSERT(myLockStatus() == KstRWLock::WRITELOCKED);

  bool force = dirty();
  setDirty(false);

  if (KstObject::checkUpdateCounter(update_counter) && !force) {
    return lastUpdateResult();
  }

  if (recursed()) {
    return setLastUpdateResult(NO_CHANGE);
  }

  writeLockInputsAndOutputs();

  KstVectorPtr iv = _inputVectors[INVECTOR];

  if (update_counter <= 0) {
    assert(update_counter == 0);
    force = true;
  }

  bool xUpdated = KstObject::UPDATE == iv->update(update_counter);

  const int v_len = iv->length();

  // Don't touch _last_n_new if !xUpdated since it will certainly be wrong.
  if (!xUpdated && !force) {
    unlockInputsAndOutputs();
    return setLastUpdateResult(NO_CHANGE);
  }

  _last_n_new += iv->numNew();
  assert(_last_n_new >= 0);

  int n_subsets = v_len/_PSDLen;

  // determine if the PSD needs to be updated. if not using averaging, then we need at least _PSDLen/16 new data points. if averaging, then we want enough new data for a complete subset.
  if ( ((_last_n_new < _PSDLen/16) || (_Average && (n_subsets - _last_n_subsets < 1))) &&  iv->length() != iv->numNew() && !force) {
    unlockInputsAndOutputs();
    return setLastUpdateResult(NO_CHANGE);
  }

  _adjustLengths();

  double *psd = (*_sVector)->value();
  double *f = (*_fVector)->value();

  int i_samp;
  for (i_samp = 0; i_samp < _PSDLen; ++i_samp) {
    f[i_samp] = i_samp * 0.5 * _Freq / (_PSDLen - 1);
  }

  _psdCalculator.calculatePowerSpectrum(iv->value(), v_len, psd, _PSDLen, _RemoveMean,  _interpolateHoles, _Average, _averageLen, _Apodize, _apodizeFxn, _gaussianSigma, _Output, _Freq);

  _last_n_subsets = n_subsets;
  _last_n_new = 0;

  updateVectorLabels();
  (*_sVector)->setDirty();
  (*_sVector)->update(update_counter);
  (*_fVector)->setDirty();
  (*_fVector)->update(update_counter);

  unlockInputsAndOutputs();

  return setLastUpdateResult(UPDATE);
}
Example #29
0
void renderLabel(RenderContext& rc, Label::Chunk *fi) {
  // FIXME: RTL support
  int oldSize = rc.size;
  int oldY = rc.y;
  int oldX = rc.x;
  
  while (fi) {
    if (fi->vOffset != Label::Chunk::None) {
      if (fi->vOffset == Label::Chunk::Up) {
        rc.y -= int(0.4 * rc.fontHeight());
      } else { // Down
        rc.y += int(0.4 * rc.fontHeight());
      }
      if (rc.size > 5) {
        rc.size = (rc.size*2)/3;
      }
    }

    QFont f = rc.font();
    if (rc.fontSize() != rc.size) {
      f.setPointSize(rc.size);
    }

    f.setBold(fi->attributes.bold);
    f.setItalic(fi->attributes.italic);
    f.setUnderline(fi->attributes.underline);
    if (rc.p && fi->attributes.color.isValid()) {
      rc.p->setPen(fi->attributes.color);
    } else if (rc.p) {
      rc.p->setPen(rc.pen);
    }
    rc.setFont(f);

    if (fi->linebreak) {
      rc.x = oldX;
      rc.y += rc.fontAscent() + rc.fontDescent() + 1;
      fi = fi->next;
      continue;
    }

    if (!rc.substitute && (fi->scalar || fi->vector)) {
      QString txt = QString("[") + fi->text + "]";
      if (rc.p) {
        rc.p->drawText(rc.x, rc.y, txt);
      }
      rc.x += rc.fontWidth(txt);
    } else if (fi->scalar) { 
      // do scalar/string/fit substitution
      QString txt;
      if (!fi->text.isEmpty() && fi->text[0] == '=') {
        // Parse and evaluate as an equation
        bool ok = false;
        const double eqResult(Equation::interpret(fi->text.mid(1).latin1(), &ok));
        txt = QString::number(eqResult, 'g', rc.precision);
        if (rc._cache) {
          rc._cache->append(DataRef(DataRef::DRExpression, fi->text, QString::null, 0.0, QVariant(eqResult)));
        }
      } else {
        KST::scalarList.lock().readLock();
        KstScalarPtr scp = *KST::scalarList.findTag(fi->text);
        KST::scalarList.lock().unlock();
        if (scp) {
          scp->readLock();
          txt = QString::number(scp->value(), 'g', rc.precision);
          if (rc._cache) {
            rc._cache->append(DataRef(DataRef::DRScalar, fi->text, QString::null, 0.0, QVariant(scp->value())));
          }
          scp->unlock();
        } else {
          KST::stringList.lock().readLock();
          KstStringPtr stp = *KST::stringList.findTag(fi->text);
          KST::stringList.lock().unlock();
          if (stp) {
            stp->readLock();
            txt = stp->value();
            if (rc._cache) {
              rc._cache->append(DataRef(DataRef::DRString, fi->text, QString::null, 0.0, QVariant(stp->value())));
            }
            stp->unlock();
          } else {
            KST::dataObjectList.lock().readLock();
            KstDataObjectList::Iterator oi = KST::dataObjectList.findTag(fi->text);
            KST::dataObjectList.lock().unlock();
            if (oi != KST::dataObjectList.end()) {
              KstPluginPtr fit = kst_cast<KstPlugin>(*oi);
              if (fit) {
                fit->readLock();
                const QString txtAll = fit->label(rc.precision);
                fit->unlock();
                
                const QValueList<QString> strList = QStringList::split('\n', txtAll);
                QValueListConstIterator<QString> last = --(strList.end());
                for (QValueListConstIterator<QString> iter = strList.begin(); iter != strList.end(); ++iter) {
                  txt = (*iter);

                  if (iter != last) {
                    if (rc.p) {
                      rc.p->drawText(rc.x, rc.y, txt);
                    } else {
                      rc.ascent = kMax(rc.ascent, -rc.y + rc.fontAscent());
                      if (-rc.y - rc.fontDescent() < 0) {
                        rc.descent = kMax(rc.descent, rc.fontDescent() + rc.y);
                      }
                    }
                    rc.x   += rc.fontWidth(txt);
                    rc.xMax = kMax(rc.xMax, rc.x);
                  
                    rc.x    = oldX;
                    rc.y   += rc.fontAscent() + rc.fontDescent() + 1;
                  }
                }                
                if (rc._cache) {
                  rc._cache->append(DataRef(DataRef::DRFit, fi->text, txtAll, rc.precision, QVariant(0.0)));
                }
              }
            }
          }
        }
      }
      if (rc.p) {
        rc.p->drawText(rc.x, rc.y, txt);
      }
      rc.x += rc.fontWidth(txt);
    } else if (fi->vector) {
      QString txt;
      KST::vectorList.lock().readLock();
      KstVectorPtr vp = *KST::vectorList.findTag(fi->text);
      KST::vectorList.lock().unlock();
      if (vp) {
        if (!fi->expression.isEmpty()) {
          // Parse and evaluate as an equation
          bool ok = false;
          // FIXME: make more efficient: cache the parsed equation
          const double idx = Equation::interpret(fi->expression.latin1(), &ok);
          if (ok) {
            vp->readLock();
            const double vVal(vp->value()[int(idx)]);
            txt = QString::number(vVal, 'g', rc.precision);
            if (rc._cache) {
              rc._cache->append(DataRef(DataRef::DRVector, fi->text, fi->expression, idx, QVariant(vVal)));
            }
            vp->unlock();
          } else {
            txt = "NAN";
          }
        }
      }
      if (rc.p) {
        rc.p->drawText(rc.x, rc.y, txt);
      }
      rc.x += rc.fontWidth(txt);
    } else if (fi->tab) {
      const int tabWidth = rc.fontWidth("MMMMMMMM");
      const int toSkip = tabWidth - (rc.x - rc.xStart) % tabWidth;
      if (rc.p && fi->attributes.underline) {
        const int spaceWidth = rc.fontWidth(" ");
        const int spacesToSkip = tabWidth / spaceWidth + (tabWidth % spaceWidth > 0 ? 1 : 0);
        rc.p->drawText(rc.x, rc.y, QString().fill(' ', spacesToSkip));
      }
      rc.x += toSkip;
    } else {
      if (rc.p) {
#ifdef BENCHMARK
        QTime t;
        t.start();
#endif
        rc.p->drawText(rc.x, rc.y, fi->text);
#ifdef BENCHMARK
        kstdDebug() << "Renderer did draw, time: " << t.elapsed() << endl;
#endif
      }
      rc.x += rc.fontWidth(fi->text);
    }

    if (!rc.p) {
      // No need to compute ascent and descent when really painting
      rc.ascent = kMax(rc.ascent, -rc.y + rc.fontAscent());
      if (-rc.y - rc.fontDescent() < 0) {
        rc.descent = kMax(rc.descent, rc.fontDescent() + rc.y);
      }
    }

    int xNext = rc.x;
    if (fi->group) {
      renderLabel(rc, fi->group);
      xNext = rc.x;
    }

    if (fi->up) {
      int xPrev = rc.x;
      renderLabel(rc, fi->up);
      xNext = kMax(xNext, rc.x);
      rc.x = xPrev;
    }

    if (fi->down) {
      renderLabel(rc, fi->down);
      xNext = kMax(xNext, rc.x);
    }

    rc.x = xNext;
    rc.xMax = kMax(rc.xMax, rc.x);

    fi = fi->next;
  }

  rc.size = oldSize;
  rc.y = oldY;
}
void doTests() {

  KstVectorPtr vp = new KstVector(KstObjectTag::fromString("tempVector"), 10);
  for (int i = 0; i < 10; i++){
    vp->value()[i] = i;
  }

  KstPSDPtr psd = new KstPSD(QString("psdTest"), vp, 0.0, false, 10, false, false, QString("vUnits"), QString("rUnits"), WindowUndefined, 0.0, PSDUndefined);
  doTest(psd->tagName() == "psdTest");
  doTest(psd->vTag() == "tempVector");
  doTest(psd->output() == PSDUndefined);
  doTest(!psd->apodize());
  doTest(!psd->removeMean());
  doTest(!psd->average());
  doTest(psd->freq() == 0.0);
  doTest(psd->apodizeFxn() == WindowUndefined);
  doTest(psd->gaussianSigma() == 0);
  KstVectorPtr vpVX = psd->vX();
  KstVectorPtr vpVY = psd->vY();

  doTest(vpVX->length() == 1);
  doTest(vpVX->value()[0] != vpVX->value()[0]);
  doTest(vpVY->length() == 1);
  doTest(vpVY->value()[0] != vpVY->value()[0]);

  psd->writeLock();
  doTest(psd->update(0) == KstObject::UPDATE);
  psd->unlock();
 
  for(int j = 0; j < vpVX->length(); j++){
      doTest(vpVX->value()[j] == 0);
  }

  psd->setOutput(PSDAmplitudeSpectralDensity);
  psd->setApodize(true);
  psd->setRemoveMean(true);
  psd->setAverage(true);
  psd->setFreq(0.1);
  psd->setApodizeFxn(WindowOriginal);
  psd->setGaussianSigma(0.2);

  doTest(psd->tagName() == "psdTest");
  doTest(psd->vTag() == "tempVector");
  doTest(psd->output() == PSDAmplitudeSpectralDensity);
  doTest(psd->apodize());
  doTest(psd->removeMean());
  doTest(psd->average());
  doTest(psd->freq() == 0.1);
  doTest(psd->apodizeFxn() == WindowOriginal);
  doTest(psd->gaussianSigma() == 0.2);
  
//   doTest(psd->update(0) == KstObject::UPDATE);
//   QString ps = "PSD: " + psd->vTag();
//   doTest(psd->propertyString() == ps);
//    doTest(!psd->curveHints().curveName() == "");
//   printf("Curve name [%s]", kstCHL[0].curveName());
//   printf("X Vector name [%s]", kstCHL[0].xVectorName());
//   printf("Y Vector name [%s]", kstCHL[0].yVectorName());

  QTemporaryFile tf;
  tf.open();
  QTextStream ts(&tf);
  psd->save(ts, "");
  QFile::remove(tf.fileName());

  QDomNode n = makeDOMElement("psdDOMPsd", "psdDOMVector").firstChild();
  QDomElement e = n.toElement();
  KstPSDPtr psdDOM = new KstPSD(e);

  doTest(psdDOM->tagName() == "psdDOMPsd");
  doTest(psdDOM->output() == PSDAmplitudeSpectralDensity);
  doTest(psdDOM->apodize());
  doTest(psdDOM->removeMean());
  doTest(psdDOM->average());
  doTest(psdDOM->freq() == 128);
  doTest(psdDOM->apodizeFxn() == WindowOriginal);
  doTest(psdDOM->gaussianSigma() == 0.01);

//   KstVectorPtr vpVX = psdDOM->vX();
//   for(int j = 0; j < vpVX->length(); j++){
//       printf("[%d][%lf]", j, vpVX->value()[j]);
//   }
//   KstVectorPtr vpVY = psdDOM->vY();
}