Example #1
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 #2
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 #4
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 #5
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 #6
0
void KstHistogram::AutoBin(KstVectorPtr V, int *n, double *max, double *min) {
  double m;

  *max = V->max();
  *min = V->min();
  *n = V->length();

  if (*max < *min) {
    m = *max;
    *max = *min;
    *min = m;
  }
  
  if (*max == *min) {
    *max += 1.0;
    *min -= 1.0;
  }

  // we can do a better job auto-ranging using the tick rules from plot...
  // this has not been done yet, you will notice...
  *n /= 50;
  if (*n < 6) {
    *n = 6;
  }
  if (*n > 60) {
    *n = 60;
  }

  m = (*max - *min)/(100.0*double(*n));
  *max += m;
  *min -= m;
}
Example #7
0
bool doTest(const char *equation, double x, double result, const double tol = 0.00000000001) {
  yy_scan_string(equation);
  int rc = yyparse();
  if (rc == 0) {
    vectorsUsed.clear();
    Equation::Node *eq = static_cast<Equation::Node*>(ParsedEquation);
    assert(eq);
    ParsedEquation = 0L;
    Equation::Context ctx;
    ctx.sampleCount = 2;
    ctx.noPoint = NOPOINT;
    ctx.x = x;
    ctx.xVector = xVector;
    if (xVector) {
      ctx.sampleCount = xVector->length();
    }
    Equation::FoldVisitor vis(&ctx, &eq);
    if (eq->isConst() && !dynamic_cast<Equation::Number*>(eq)) {
      if (!optimizerFailed) {
        optimizerFailed = true;
        ::rc--;
        printf("Optimizer bug: found an unoptimized const equation.  Optimizing for coverage purposes.\n");
      }
      double v = eq->value(&ctx);
      delete eq;
      eq = new Equation::Number(v);
    }
    KstScalarMap scm;
    KstStringMap stm;
    eq->collectObjects(vectorsUsed, scm, stm);

    //
    // do not use -1 in the call to eq->update( ... ) 
    //  as this will simply return without updating the plugin,
    //  unless an underlying data object was updated...
    //
    eq->update(0, &ctx);
    double v = eq->value(&ctx);
    delete eq;
    if (fabs(v - result) < tol || (result != result && v != v) || (result == INF && v == INF) || (result == -INF && v == -INF)) {
      return true;
    } else {
      printf("Result: %.16f\n", v);
      return false;
    }
  } else {
    // Parse error
    printf("Failures on [%s] -------------------------\n", equation);
    for (QStringList::ConstIterator i = Equation::errorStack.constBegin(); i != Equation::errorStack.constEnd(); ++i) {
      printf("%s\n", (*i).latin1());
    }
    printf("------------------------------------------\n");
    delete (Equation::Node*)ParsedEquation;
    ParsedEquation = 0L;
    return false;
  }
}
Example #8
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 #9
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;
}
void BinnedMap::AutoSize(KstVectorPtr x, KstVectorPtr y, int *nx, double *minx, double *maxx, int *ny, double *miny, double *maxy) {

  // use a very simple guess at nx and ny... One could imagine something more
  // clever in principle.
  *nx = *ny = (int)sqrt(x->length())/2;
  if (*nx<2) *nx = 2;
  if (*ny<2) *ny = 2;

  *minx = x->min();
  *maxx = x->max();
  *miny = y->min();
  *maxy = y->max();
}
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 #12
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;
}
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 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;
}
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 #16
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 #18
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 #19
0
void BinnedMap::binnedmap() {
    KstVectorPtr x = *_inputVectors.find(VECTOR_X);
    KstVectorPtr y = *_inputVectors.find(VECTOR_Y);
    KstVectorPtr z = *_inputVectors.find(VECTOR_Z);
    KstMatrixPtr map = *_outputMatrices.find(MAP);
    KstMatrixPtr hitsMap = *_outputMatrices.find(HITSMAP);
    KstScalarPtr autobin = *_inputScalars.find(AUTOBIN);

    if (autobin) {
        if (autobin->value() != 0.0) {
            _autoBin = true;
        } else {
            _autoBin = false;
        }
    }

    if (_autoBin) {
        double minx, miny, maxx, maxy;
        int nx, ny;

        autoSize(X(), Y(), &nx, &minx, &maxx, &ny, &miny, &maxy);

        setNX(nx);
        setNY(ny);
        setXMin(minx);
        setXMax(maxx);
        setYMin(miny);
        setYMax(maxy);
    } else {
        KstScalarPtr xmin = *_inputScalars.find(XMIN);
        KstScalarPtr xmax = *_inputScalars.find(XMAX);
        KstScalarPtr ymin = *_inputScalars.find(YMIN);
        KstScalarPtr ymax = *_inputScalars.find(YMAX);
        KstScalarPtr nx = *_inputScalars.find(NX);
        KstScalarPtr ny = *_inputScalars.find(NY);

        if (xmin) {
            _xMin = xmin->value();
        }
        if (xmax) {
            _xMax = xmax->value();
        }
        if (ymin) {
            _yMin = ymin->value();
        }
        if (ymax) {
            _yMax = ymax->value();
        }
        if (nx) {
            _nx = (int)nx->value();
        }
        if (ny) {
            _ny = (int)ny->value();
        }
    }

    bool needsresize = false;

    if (_nx < 2) {
        _nx = 2;
        needsresize = true;
    }
    if (_ny < 2) {
        _ny = 2;
        needsresize = true;
    }

    if ((map->xNumSteps() != _nx) || (map->yNumSteps() != _ny) ||
            (map->minX() != _xMin) || (map->minY() != _yMin)) {
        needsresize = true;
    }

    if (map->xStepSize() != (_xMax - _xMin)/double(_nx-1)) {
        needsresize = true;
    }
    if (map->yStepSize() != (_yMax - _yMin)/double(_ny-1)) {
        needsresize = true;
    }

    if (needsresize) {
        map->change(map->tag(), _nx, _ny, _xMin, _yMin,
                    (_xMax - _xMin)/double(_nx-1), (_yMax - _yMin)/double(_ny-1));
        map->resize(_nx, _ny);
        hitsMap->change(hitsMap->tag(), _nx, _ny, _xMin, _yMin,
                        (_xMax - _xMin)/double(_nx-1), (_yMax - _yMin)/double(_ny-1));
        hitsMap->resize(_nx, _ny);
    }

    map->zero();
    hitsMap->zero();

    int ns = z->length(); // the z vector defines the number of points.
    double n,p, x0, y0, z0;

    for (int i=0; i<ns; i++) {
        x0 = x->interpolate(i, ns);
        y0 = y->interpolate(i, ns);
        z0 = z->interpolate(i, ns);
        p = map->value(x0, y0)+z0;
        map->setValue(x0, y0, p);
        n = hitsMap->value(x0, y0)+1;
        hitsMap->setValue(x0, y0, n);
    }

    for (int i=0; i<_nx; i++) {
        for (int j=0; j<_ny; j++) {
            p = map->valueRaw(i, j);
            n = hitsMap->valueRaw(i, j);
            if (n>0) {
                map->setValueRaw(i, j, p/n);
            } else {
                map->setValueRaw(i, j, KST::NOPOINT);
            }
        }
    }
}
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);
  }
  
  // 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 #21
0
void KstObjectItem::update(bool recursive, int localUseCount) {
  switch (_rtti) {
    case RTTI_OBJ_DATA_VECTOR:
    {
      KST::vectorList.lock().readLock();
      KstRVectorPtr x = kst_cast<KstRVector>(*KST::vectorList.findTag(_tag));
      KST::vectorList.lock().unlock();
      if (x) {
        x->readLock();
        // getUsage: subtract 1 for KstRVectorPtr x
        bool inUse = (x->getUsage() - 1 - localUseCount) > 0;
        if (inUse != _inUse) {
          _inUse = inUse;
          setPixmap(2, inUse ? _dm->yesPixmap() : QPixmap());
        }
        QString field;
        if (inUse) {
          field = QString::number(x->length());
        } else {
          field = "-";
        }
        if (text(3) != field) {
          setText(3, field);
        }
        field = i18n("%3: %4 [%1..%2]").arg(x->reqStartFrame())
            .arg(x->reqStartFrame() + x->reqNumFrames())
            .arg(x->filename())
            .arg(x->field());
        if (text(4) != field) {
          setText(4, field);
        }
        _removable = x->getUsage() == 2;
        x->unlock();
      }
      // Hmmm what happens if this if() fails??  We become inconsistent?
      break;
    }
    case RTTI_OBJ_STATIC_VECTOR:
    {
      KST::vectorList.lock().readLock();
      KstSVectorPtr x = kst_cast<KstSVector>(*KST::vectorList.findTag(_tag));
      KST::vectorList.lock().unlock();
      if (x) {
        x->readLock();
        // getUsage: subtract 1 for KstRVectorPtr x
        bool inUse = (x->getUsage() - 1 - localUseCount) > 0;
        if (inUse != _inUse) {
          _inUse = inUse;
          setPixmap(2, inUse ? _dm->yesPixmap() : QPixmap());
        }
        QString field;
        if (inUse) {
          field = QString::number(x->length());
        } else {
          field = "-";
        }
        if (text(3) != field) {
          setText(3, field);
        }
        field = i18n("%1 to %2").arg(x->min()).arg(x->max());
        if (text(4) != field) {
          setText(4, field);
        }
        _removable = x->getUsage() == 2;
        x->unlock();
      }
      // Hmmm what happens if this if() fails??  We become inconsistent?
      break;
    }
    case RTTI_OBJ_VECTOR:
    {
      KST::vectorList.lock().readLock();
      KstVectorPtr x = *KST::vectorList.findTag(_tag);
      KST::vectorList.lock().unlock();
      if (x) {
        x->readLock();
        // getUsage:
        //  subtract 1 for KstVectorPtr x
        bool inUse = (x->getUsage() - 1 - localUseCount) > 0;
        if (inUse != _inUse) {
          _inUse = inUse;
          setPixmap(2, inUse ? _dm->yesPixmap() : QPixmap());
        }
        QString field = QString::number(x->length());
        if (text(3) != field) {
          setText(3, field);
        }
        field = i18n("[%1..%2]").arg(x->min()).arg(x->max());
        if (text(4) != field) {
          setText(4, field);
        }
        x->unlock();
        _removable = false;
      }
      break;
    }
    case RTTI_OBJ_OBJECT:
    {
      KST::dataObjectList.lock().readLock();
      KstDataObjectPtr x = *KST::dataObjectList.findTag(_tag.tag());
      KST::dataObjectList.lock().unlock();
      if (x) {
        x->readLock();
        QString field = x->typeString();
        if (text(1) != field) {
          setText(1, field);
        }
        // getUsage:
        //  subtract 1 for KstDataObjectPtr x
        bool inUse = (x->getUsage() - 1 - localUseCount) > 0;
        if (inUse != _inUse) {
          _inUse = inUse;
          setPixmap(2, inUse ? _dm->yesPixmap() : QPixmap());
        }
        if (x->sampleCount() > 0) {
          field = QString::number(x->sampleCount());
          if (text(3) != field) {
            setText(3, field);
          }
        } else {
          if (text(3) != "-") {
            setText(3, "-");
          }          
        }
        field = x->propertyString();
        if (text(4) != field) {
          setText(4, field);
        }
        if (recursive) {
          QPtrStack<QListViewItem> trash;
          KstVectorMap vl = x->outputVectors();
          KstVectorMap::Iterator vlEnd = vl.end();

          for (QListViewItem *i = firstChild(); i; i = i->nextSibling()) {
            KstObjectItem *oi = static_cast<KstObjectItem*>(i);
            if (vl.findTag(oi->tag().tag()) == vlEnd) {
              trash.push(i);
            }
          }
          trash.setAutoDelete(true);
          trash.clear();

          // get the output vectors
          for (KstVectorMap::Iterator p = vl.begin(); p != vlEnd; ++p) {
            bool found = false;
            QString tn = p.data()->tag().tag();
            for (QListViewItem *i = firstChild(); i; i = i->nextSibling()) {
              KstObjectItem *oi = static_cast<KstObjectItem*>(i);
              if (oi->tag().tag() == tn) {
                oi->update();
                found = true;
                break;
              }
            }
            if (!found) {
              KstObjectItem *item = new KstObjectItem(this, p.data(), _dm);
              connect(item, SIGNAL(updated()), this, SIGNAL(updated()));
            }
          }
          
          KstMatrixMap ml = x->outputMatrices();
          KstMatrixMap::Iterator mlEnd = ml.end();
          // also get the output matrices
          for (KstMatrixMap::Iterator p = ml.begin(); p != mlEnd; ++p) {
            bool found = false;
            QString tn = p.data()->tag().tag();
            for (QListViewItem *i = firstChild(); i; i = i->nextSibling()) {
              KstObjectItem *oi = static_cast<KstObjectItem*>(i);
              if (oi->tag().tag() == tn) {
                oi->update();
                found = true;
                break;
              }
            }
            if (!found) {
              KstObjectItem *item = new KstObjectItem(this, p.data(), _dm);
              connect(item, SIGNAL(updated()), this, SIGNAL(updated()));
            }
          }
        }
        _removable = x->getUsage() == 1;
        x->unlock();
      }
      break;
    }
    case RTTI_OBJ_DATA_MATRIX:
    {
      KST::matrixList.lock().readLock();
      KstRMatrixPtr x = kst_cast<KstRMatrix>(*KST::matrixList.findTag(_tag));
      KST::matrixList.lock().unlock();
      if (x) {
        x->readLock();
          // getUsage: subtract 1 for KstRMatrixPtr x
        bool inUse = (x->getUsage() - 1 - localUseCount) > 0;
        if (inUse != _inUse) {
          _inUse = inUse;
          setPixmap(2, inUse ? _dm->yesPixmap() : QPixmap());
        }
        QString field = QString::number(x->sampleCount());
        if (text(3) != field) {
          setText(3, field);
        }
        field = i18n("%1: %2 (%3 by %4)").arg(x->filename()).arg(x->field())
                .arg(x->xNumSteps())
                .arg(x->yNumSteps()); 
        if (text(4) != field) {
          setText(4, field);
        }
        _removable = x->getUsage() == 2;
        x->unlock();
      } 
      break;
    }
    case RTTI_OBJ_STATIC_MATRIX:
    {
      KST::matrixList.lock().readLock();
      KstSMatrixPtr x = kst_cast<KstSMatrix>(*KST::matrixList.findTag(_tag));
      KST::matrixList.lock().unlock();
      if (x) {
        x->readLock();
          // getUsage: subtract 1 for KstRMatrixPtr x
        bool inUse = (x->getUsage() - 1 - localUseCount) > 0;
        if (inUse != _inUse) {
          _inUse = inUse;
          setPixmap(2, inUse ? _dm->yesPixmap() : QPixmap());
        }
        QString field = QString::number(x->sampleCount());
        if (text(3) != field) {
          setText(3, field);
        }
        field = i18n("%1 to %2").arg(x->gradZMin()).arg(x->gradZMax());
        if (text(4) != field) {
          setText(4, field);
        }
        _removable = x->getUsage() == 2;
        x->unlock();
      }
      break;
    }
    case RTTI_OBJ_MATRIX:
    {
      KST::matrixList.lock().readLock();
      KstMatrixPtr x = *KST::matrixList.findTag(_tag);
      KST::matrixList.lock().unlock();
      if (x) {
        x->readLock();
          // getUsage:
          //  subtract 1 for KstVectorPtr x
        bool inUse = (x->getUsage() - 1 - localUseCount) > 0;
        if (inUse != _inUse) {
          _inUse = inUse;
          setPixmap(2, inUse ? _dm->yesPixmap() : QPixmap());
        }
        QString field = QString::number(x->sampleCount());
        if (text(3) != field) {
          setText(3, field);
        }
        field = i18n("[%1..%2]").arg(x->minValue()).arg(x->maxValue());
        if (text(4) != field) {
          setText(4, field);
        }
        x->unlock();
        _removable = false;
      }
      break;
    }
    default:
      assert(0);
  }
}
Example #22
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();
}
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);
}
Example #24
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;
}
Example #25
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 #26
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();
}
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;
}
void BinnedMap::binnedmap() {
  KstVectorPtr x = *_inputVectors.find(VECTOR_X);
  KstVectorPtr y = *_inputVectors.find(VECTOR_Y);
  KstVectorPtr z = *_inputVectors.find(VECTOR_Z);

  KstMatrixPtr map = *_outputMatrices.find(MAP);
  KstMatrixPtr hitsMap = *_outputMatrices.find(HITSMAP);

  if (autoBin()) {
    AutoSize(X(),Y(), &_nx, &_xMin, &_xMax, &_ny, &_yMin, &_yMax);
  }
  
  bool needsresize = false;
  if (_nx<2) {
    _nx = 2;
    needsresize = true;
  }
  if (_ny<2) {
    _ny = 2;
    needsresize = true;
  }
  
  if ((map->xNumSteps() != _nx) || (map->yNumSteps() != _ny) ||
       (map->minX() != _xMin) || (map->minY() != _yMin)) {
    needsresize = true;
  }
  
  if (map->xStepSize() != (_xMax - _xMin)/double(_nx-1)) {
    needsresize = true;
  }
  if (map->yStepSize() != (_yMax - _yMin)/double(_ny-1)) {
    needsresize = true;
  }
  
  if (needsresize) {
    map->change(map->tag(), _nx, _ny, _xMin, _yMin,
		(_xMax - _xMin)/double(_nx-1), (_yMax - _yMin)/double(_ny-1));
    map->resize(_nx, _ny);
    hitsMap->change(hitsMap->tag(), _nx, _ny, _xMin, _yMin,
		(_xMax - _xMin)/double(_nx-1), (_yMax - _yMin)/double(_ny-1));
    hitsMap->resize(_nx, _ny);
  }

  map->zero();
  hitsMap->zero();

  int ns = z->length(); // the z vector defines the number of points.
  double n,p, x0, y0, z0;
  for (int i=0; i<ns; i++) {
    x0 = x->interpolate(i, ns);
    y0 = y->interpolate(i, ns);
    z0 = z->interpolate(i, ns);
    p = map->value(x0, y0)+z0;
    map->setValue(x0, y0, p);
    n = hitsMap->value(x0, y0)+1;
    hitsMap->setValue(x0, y0, n);
  }

  for (int i=0; i<_nx; i++) {
    for (int j=0; j<_ny; j++) {
      p = map->valueRaw(i,j);
      n = hitsMap->valueRaw(i,j);
      if (n>0) {
	map->setValueRaw(i,j,p/n);
      } else {
	map->setValueRaw(i,j,KST::NOPOINT);
      }
    }
  }

  //calculate here...
}
Example #29
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);
}
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();
}