Example #1
0
int main(void) {
	int data[13] = { 0 };
	int lowPass[33] = { 0 };
	int highPass[5] = { 0 };
	int deriv[31] = { 0 };
	int squar[31] = { 0 };
	int mwi[3] = { 0 };
	int time[8] = { 0 };
	int rPeaks[8] = { 0 };
	int counter = 0;

	for (int i = 0; i < 10000; i++) {
		data[i % 13] = getNextData();
		lowpass(data, lowPass, 13, 33, i);
		highpass(lowPass, highPass, 33, 5, i);
		derivative(highPass, deriv, 5, 31, i);
		squaring(deriv, squar, 31, 31, i);
		movingWindow(squar, mwi, 31, 3, i);
		counter = findPeaks(mwi, i, time, rPeaks);
		if (counter != -1) {
			int intensity = rPeaks[counter % 8];
			int RRinterval = time[counter % 8] - time[(counter - 1 + 8) % 8];
			int pulse = 60000 / (RRinterval * 1000 / 250);
			printf("R-Peak intensity: %d\nTime-value: %d s (%d samples)\nRR-interval: %d\nPulse: %d beats/minute\n\n",
					intensity, i / 250, i, RRinterval, pulse);
			if (rPeaks[counter % 8] < 2000) {
				printf("WARNING! low R-peak value\n");
			}
		}
	}
	return 0;
}
Example #2
0
void WaveRenderArea::setData(const SampleBufferType &data, qint64 processedUSecs)
{
  Q_D(WaveRenderArea);
  QMutexLocker(d->sampleBufferMutex);
  d->sampleBuffer = data;
  d->frameTimestampNs = 1000 * processedUSecs;
  findPeaks();
  d->lastFrameTimestampNs = d->frameTimestampNs;
  drawPixmap();
}
Example #3
0
//given a large patch and a smaller patch, finds the peak of teh NCC value to compute translation between patches
void findMatchingTranslation(IplImage *imageIpl,IplImage *templIpl,double *x,double *y,double *score,int mType)
{
    int lP_width=imageIpl->width;
    int lP_height=imageIpl->height;
    int sP_width=templIpl->width;
    //int sP_height=templIpl->height;
    int result_width = lP_width - sP_width + 1;
    int result_height = lP_height - sP_width + 1;

    IplImage* resultIpl = cvCreateImage(cvSize(result_width, result_height), IPL_DEPTH_32F, 1);


    cvMatchTemplate(imageIpl, templIpl, resultIpl, CV_TM_CCOEFF_NORMED);


    //famattodo: crop borders. Is it necessary using NCC from OpenCV? I don't think so.
    vector<Point2D*> peaks = findPeaks((float*)resultIpl->imageData, result_width, result_height, peakThresholdFillContours, 1, 0, sP_width, 0,mType);


    //famatdebug
    //ofstream outfv("result_fc.txt");
    //print(resultIpl,outfv);
    //outfv.close();
    //cout<<"Finished writing translation matching with (x,y)="<<*peaks[0]<<endl;
    //cout<<"peaks size="<<peaks.size()<<endl;
    //--------------------------

    cvReleaseImage(&resultIpl);

    if (!peaks.empty())
    {
        *x=peaks[0]->x;
        *y=peaks[0]->y;
        *score=peaks[0]->score;
    }
    else
    {
        *x=-1.0;
        *y=-1.0;
        *score=-1.0;
    }


    //deallocate memory for peaks
    for (unsigned int kk=0; kk<peaks.size(); kk++)
        delete peaks[kk];
    peaks.clear();

}
Example #4
0
void beadCenter(IplImage *patchIpl,IplImage *perfectMarkerTemplIpl,float *xx,float *yy,int mType)
{
    int result_width = patchIpl->width - perfectMarkerTemplIpl->width + 1;
    int result_height = patchIpl->height - perfectMarkerTemplIpl->height + 1;

    IplImage *resultIpl = cvCreateImage(cvSize(result_width, result_height), IPL_DEPTH_32F, 1);
    cvMatchTemplate(patchIpl, perfectMarkerTemplIpl, resultIpl, CV_TM_CCOEFF_NORMED);

    //famatdebug
    //ofstream outTempl("resultBeadCenter_fc.txt");
    //print(resultIpl,outTempl);
    //outTempl.close();
    //cout<<"Finished writing result bead center"<<endl;
    //----------------

    //we find the closest peak to (xx,yy)
    //note:highest peak is not always the best option (for example, when two markers are together)

    //famattodo: crop borders. Is it necessary using NCC from OpenCV? I don't think so.
    int maxNumPeaks=5;
    vector<Point2D*> peaks = findPeaks((float*)resultIpl->imageData, result_width, result_height, peakThresholdFillContours, maxNumPeaks, 0, perfectMarkerTemplIpl->width, 0,mType);

    //find the closest peak
    //at the most we allow a move as largar as ther adius of a marker
    double minDist=0.25*(perfectMarkerTemplIpl->width-1);
    double dist=1e11;
    //the center is 0.5*(result->width-1). The -1 is because array limits are from 0->width-1
    float cx=0.5f*(result_width-1),cy=0.5f*(result_height-1);//findPeaks returns (x,y) coodinates in array result. We need (delta_x,delta_y)
    for(unsigned int kk=0; kk<peaks.size(); kk++)
    {
        dist=min(dist,sqrt((double)(*xx-(peaks[kk]->x-cx))*(*xx-(peaks[kk]->x-cx))+(*yy-(peaks[kk]->y-cy))*(*yy-(peaks[kk]->y-cy))));
        if(dist<minDist)
        {
            (*xx)=peaks[kk]->x-cx;
            (*yy)=peaks[kk]->y-cy;
        }
        delete peaks[kk];//deallocate memory for peaks
    }

    //deallocate memory
    peaks.clear();
    cvReleaseImage(&resultIpl);
}
Example #5
0
void canny(FILE* inputImageFile, FILE* outputMagnitudes, FILE* outputPeaks, FILE* outputFinal, double sigma){
    Mask mask;
    int picBuffer[PICSIZE][PICSIZE];
    double itsMagnitudes[PICSIZE][PICSIZE];
    double maxMagnitude;
    GradientVector usingGradients;
    double peaks[PICSIZE][PICSIZE];
    double final[PICSIZE][PICSIZE];

    readImageTo(picBuffer, inputImageFile);
    mask = generateSmoothenerMask(sigma);
    usingGradients = calculateGradients(picBuffer, mask);
    calculateMagnitudes(usingGradients, mask.radius, itsMagnitudes);
    maxMagnitude = findMaxValue(itsMagnitudes);
    scaleImageWithRespectTo(maxMagnitude, itsMagnitudes);

    findPeaks(itsMagnitudes, usingGradients, mask.radius, peaks);
    Threshold threshold = getThreshold(itsMagnitudes);
    applyHysteresisThresholdTo(itsMagnitudes, usingGradients, mask.radius, 
                                peaks, threshold, final);
    writeTo(outputMagnitudes, itsMagnitudes);
    writeTo(outputPeaks, peaks);
    writeTo(outputFinal, final);
}
features_t getFeatures(vector<int> leftEyeDistances, vector<int> rightEyeDistances)
{
	vector<int> distances;
	int i;
	features_t features;

	for (i = 0; i < leftEyeDistances.size(); i++)
	{
		distances.push_back((int)round((leftEyeDistances[i] + rightEyeDistances[i]) / 2.0));
	}
	
	int minVal, maxVal;
	int minInd, maxInd;
	vectorGetMax(distances, &maxVal, &maxInd);
	vectorGetMin(distances, &minVal, &minInd);

	double threshold = 0.9 * (minVal + maxVal) / 2.0;
	vector<int> eyeClosed = ourFind(vectorTo01(distances, threshold));
	
	/* Percentage of eyelid closure */
	features.PERCLOS = eyeClosed.size() / (double)distances.size();

	/* Maximum closed duration */
	features.MCD = 0;
	int summary = 1;
	for (i = 1; i < eyeClosed.size(); i++)
	{
		if (eyeClosed[i] == eyeClosed[i - 1] + 1)
		{
			summary++;
		}
		else
		{
			if (features.MCD < summary)
			{
				features.MCD = summary;
			}
			summary = 1;
		}

		if (i == eyeClosed.size() - 1)
		{
			if (features.MCD < summary)
			{
				features.MCD = summary;
			}
			summary = 1;
		}
	}

	features.MCD *= SAMPLING_PERIOD;

	/* Blinking frequency */
	vector<int> negatedDistances = negateVector(distances);
	vector<int> locs;
	vector<int> peaks;

	findPeaks(&negatedDistances, &locs, &peaks, -(int)round(threshold));

	features.BF = 60 * peaks.size() / ((double)distances.size() * SAMPLING_PERIOD);

	/* Opening velocity and closing velocity */
	int cntClosing = 0;
	int cntOpening = 0;

	vector<int> diffPos = diff(&distances);
	vector<int> diffNeg = negateVector(diffPos);
	vector<int> locsPos;
	vector<int> locsNeg;
	vector<int> peaksPos;
	vector<int> peaksNeg;

	findPeaks(&diffPos, &locsPos, &peaksPos);
	findPeaks(&diffNeg, &locsNeg, &peaksNeg);

	vector<int> locsAll = locsPos;
	locsAll.insert(locsAll.end(), locsNeg.begin(), locsNeg.end());
	locsAll.insert(locsAll.end(), locs.begin(), locs.end());
	sort(locsAll.begin(), locsAll.end());

	int opened;
	int state;
	features.OV = 0;
	features.CV = 0;

	vector<int> locsBlink = locs;

	if (locsAll.empty())
	{
		cout << "Jebo te bog" << endl;
	}
	else
	{
		for (i = 0; i < locsAll.size() - 1; i++)
		{
			if ((find(locsPos.begin(), locsPos.end(), locsAll[i]) != locsPos.end()) ||
				(find(locsNeg.begin(), locsNeg.end(), locsAll[i]) != locsNeg.end()))
			{
				opened = 1;
			}
			else
			{
				opened = 0;
			}

			if ((find(locsPos.begin(), locsPos.end(), locsAll[i + 1]) != locsPos.end()) ||
				(find(locsNeg.begin(), locsNeg.end(), locsAll[i + 1]) != locsNeg.end()))
			{
				if (opened)
				{
					state = 0;
				}
				else
				{
					state = 1;
				}
			}
			else
			{
				if (opened)
				{
					state = -1;
				}
				else
				{
					state = 0;
				}
			}

			if(state == -1)
			{
				features.CV += abs(distances[locsAll[i]] - distances[locsAll[i+1]]) /
					abs(locsAll[i] - locsAll[i + 1]); /* pixels/frame */
				cntClosing++;
			}
			else if (state == 1)
			{
				features.OV += abs(distances[locsAll[i]] - distances[locsAll[i + 1]]) /
					abs(locsAll[i] - locsAll[i + 1]); /* pixels/frame */
				cntOpening++;
			}
		}
		features.CV /= cntClosing;
		features.OV /= cntOpening;
	}

	vector<int> eyeOpened = ourFind(invert01(vectorTo01(distances, threshold)));
	
	int AOLSum = 0;

	for (i = 0; i < eyeOpened.size(); i++)
	{
		AOLSum += distances[i];
	}

	features.AOL = ((double)AOLSum / (double)eyeOpened.size()) / maxVal;

	return features;
}
int eyelidDistance(Mat eye, double threshold)
{
	int i;
	int j;
	int m = eye.rows;
	int n = eye.cols;
	Mat strechedEye = stretchHistogram(&eye);
	vector<int> summary = sum(&strechedEye, 2);
	vector<int> eyebrowPeaks;
	vector<int> eyebrowLocs;
	findPeaks(&summary, &eyebrowLocs, &eyebrowPeaks);
	Mat eyeBinary = binarize(&strechedEye, 55);

	if (!eyebrowLocs.empty())
	{
		if (eyebrowLocs[0] != 1 && eyebrowLocs[0] < round(m / 2.2))
		{
			eyeBinary.rowRange(0, eyebrowLocs[0] - 1) = 1;
		}
	}

	vector<double> mBinary = meanValue(&eyeBinary, 2);
	vector<double> sigmaBinary(m);

	for (i = 0; i < m; i++)
	{
		double tmpSum = 0;
		for (j = 0; j < n; j++)
		{
			tmpSum += (eyeBinary.at<uchar>(i, j) - mBinary[i])*(eyeBinary.at<uchar>(i, j) - mBinary[i]);
		}
		sigmaBinary[i] = tmpSum / n;
	}
	vector<double> difVarBinary = diff(&sigmaBinary);

	vector<double> pksBinaryPositive;
	vector<int> locsBinaryPositive;
	vector<double> pksBinaryNegative;
	vector<int> locsBinaryNegative;
	findPeaks(&difVarBinary, &locsBinaryPositive, &pksBinaryPositive);
	findPeaks(&(negateVector(difVarBinary)), &locsBinaryNegative, &pksBinaryNegative);

	vector<double> pksBinary = pksBinaryPositive;
	vector<double> negatedPeaks = negateVector(pksBinaryNegative);
	pksBinary.insert(pksBinary.end(), negatedPeaks.begin(), negatedPeaks.end());
	vector<int> locsBinary = locsBinaryPositive;
	locsBinary.insert(locsBinary.end(), locsBinaryNegative.begin(), locsBinaryNegative.end());

	int loc1, loc2;
	getDistance(pksBinary, locsBinary, &loc1, &loc2);
	int distance = abs(loc2 - loc1);

	double percent = 0;

	if (distance < threshold)
	{
		return 0;
	}
	else
	{
		if (loc1 != 0 || loc2 != 0)
		{
			if (loc1 < loc2)
			{
				Mat extract = eyeBinary.rowRange(loc1, loc2);
				vector<int> sumH = sum(&invert(&extract), 2);
				int boundariesH1;
				int boundariesH2;
				int boundariesV1;
				int boundariesV2;

				getBigInterval(sumH, &boundariesH1, &boundariesH2, 0.85);
				vector<int> sumV = sum(&invert(&extract), 1);
				getBigInterval(sumV, &boundariesV1, &boundariesV2, 0.65);

				Mat cut = extract(Range(boundariesH1, boundariesH2),
					Range(boundariesV1, boundariesV2));

				percent = 100 * (sum(cut))[0] / (double)(cut.rows * cut.cols);
			}
		}

		if (percent > 25)
		{
			return 0;
		}
		else
		{
			return distance;
		}
	}
}
Example #8
0
void AudioBuffer::findPeaks(float* pPeaks, uint32* pAt /*=0*/) const {
	findPeaks(0, m_frames, pPeaks, pAt);
}
// ######################################################################
void SimulationViewerStats::save1(const ModelComponentSaveInfo& sinfo)
{
  // Use a LINFO here since we are already slowed down by writing
  // stats, we should at least have a short debug on this fact
  LINFO("SAVING STATS TO %s",itsStatsFname.getVal().c_str());

  // Lock the file. We put this here to support multi-process in the
  // future. However, this will not work on NFS mounts.
  struct flock fl; int fd;
  lockFile(itsStatsFname.getVal().c_str(),fd,fl);

  // Since this is more or less debug info we open and flush every iteration.
  // rather than once each run.
  std::ofstream statsFile;
  statsFile.open(itsStatsFname.getVal().c_str(),std::ios_base::app);

  // get the OFS to save to, assuming sinfo is of type
  // SimModuleSaveInfo (will throw a fatal exception otherwise):
  nub::ref<FrameOstream> ofs =
    dynamic_cast<const SimModuleSaveInfo&>(sinfo).ofs;

  // also get the SimEventQueue:
  SimEventQueue *q    = dynamic_cast<const SimModuleSaveInfo&>(sinfo).q;

  // initialize our stats dump file if desired:
  if(itsFrameIdx == 0)
  {
    rutz::shared_ptr<SimReqVCXmaps> vcxm(new SimReqVCXmaps(this));
    q->request(vcxm); // VisualCortex is now filling-in the maps...

    if (itsStatsFname.getVal().size())
    {
      itsStatsFile = new std::ofstream(itsStatsFname.getVal().c_str());
      if (itsStatsFile->is_open() == false)
        LFATAL("Failed to open '%s' for writing.",
               itsStatsFname.getVal().c_str());

      // dump the settings of the model:
      getRootObject()->printout(*itsStatsFile, "# ");

      // list all our channels:
      //LFATAL("FIXME");
      // also get the SimEventQueue:

      rutz::shared_ptr<ChannelMaps> chm        = vcxm->channelmaps();
      uint                          numSubmaps = chm->numSubmaps();

      *itsStatsFile << "# CHANNELS: ";

      for(uint i = 0; i < numSubmaps; i++)
      {
        NamedImage<float> smap = chm->getRawCSmap(i);
        *itsStatsFile << smap.name() << ", ";
      }
      *itsStatsFile << std::endl;
    }
  }

  // We flush frequently since this output is debuggy in nature or it's being used
  // to collect information which needs assurance of accuracy for instance in
  // RSVP analysis. It is better to err on the side of caution.
  (*itsStatsFile).flush();
  (*itsStatsFile).close();

  // get the basic input frame info
  if (SeC<SimEventInputFrame> e = q->check<SimEventInputFrame>(this))
  {
    itsSizeX       = e->frame().getWidth();
    itsSizeY       = e->frame().getHeight();
    itsFrameNumber = (unsigned int)e->frameNum();
    itsFrameIdx    = itsFrameNumber;
  }
  else
  {
    itsFrameNumber = itsFrameIdx;
    itsFrameIdx++;
  }

  // get the latest input frame:
  // Since we are only using it's basic statistics (Height / Width) , we don't care about it's
  // blackboard status. Use SEQ_ANY then. Otherwise, this will not fetch at any rate.
  Image< PixRGB<byte> > input;
  if (SeC<SimEventRetinaImage> e = q->check<SimEventRetinaImage>(this,SEQ_ANY))
    input = e->frame().colorByte();
  else
    LINFO("No input? Check the SimEventCue.");

  // Get the current frame number or keep track on your own
  /*
  if (SeC<SimEventInputFrame> e = q->check<SimEventInputFrame>(this))
    itsFrameIdx = e->frameNum();
  else
    itsFrameIdx++;
  */

  // get the latest raw AGM:
  Image<float> agm;
  if (SeC<SimEventAttentionGuidanceMapOutput> e =
      q->check<SimEventAttentionGuidanceMapOutput>(this))
    agm = e->agm(1.0F);
  else
    LINFO("No AGM? Check the SimEventCue.");

  // if we are missing input or agm, return:
  // We also need to warn so that we know why the stats file may be empty
  bool quit = false;
  if (input.initialized() == false)
    {
      LINFO("WARNING!!! Input seems not to be initialized, so detailed stats cannot be saved.");
      quit = true;
    }
  if(agm.initialized() == false)
    {
      LINFO("WARNING!!! NO Attention Guidance MAP \"AGM\" so detailed stats cannot be saved.");
      quit = true;
    }

  if(quit == true) return;

  // update the trajectory:
  Image< PixRGB<byte> > res;
  const int w = input.getWidth();

  // save image results? if so let's prepare it
  if (itsSaveXcombo.getVal() || itsSaveYcombo.getVal())
    {
      Image<float> nagm = getMap(*q);
      res = colGreyCombo(input, nagm, itsSaveXcombo.getVal(),
                         itsDisplayInterp.getVal());
    }

  // if we are saving single channel stats save saliency stats using a compatable format
  // SEE: SingleChannel.C / saveStats(..) for more info on format
  if (itsGetSingleChannelStats.getVal())
    saveCompat(agm);

  // Save a bunch of stats?
  if (statsFile)
    {
      // start with the current simulation time:
       statsFile <<std::endl<<"= "<<q->now().msecs()
                     <<" # time of frame in ms"<<std::endl;

      // get min/max/avg and stdev and number of peaks in AGM:
      float mi, ma, av; getMinMaxAvg(agm, mi, ma, av);
      double sdev = stdev(agm);
      double peaksum; int npeaks = findPeaks(agm, 0.0f, 255.0f, peaksum);

      // find the location of max in the AGM, at scale of original input:
      float maxval; Point2D<int> maxloc;
      findMax(agm, maxloc, maxval);
      float scale = float(w) / float(agm.getWidth());
      maxloc.i = int(maxloc.i * scale + 0.4999F);
      maxloc.j = int(maxloc.j * scale + 0.4999F);
      if (res.initialized())
        {
          drawPatch(res, maxloc, 4, COL_YELLOW);
          drawPatch(res, maxloc + Point2D<int>(w, 0), 4, COL_YELLOW);
        }

      // find the location of min in the AGM, at scale of original input:
      float minval; Point2D<int> minloc;
      findMin(agm, minloc, minval);
      minloc.i = int(minloc.i * scale + 0.4999F);
      minloc.j = int(minloc.j * scale + 0.4999F);
      if (res.initialized())
        {
          drawPatch(res, minloc, 4, COL_GREEN);
          drawPatch(res, minloc + Point2D<int>(w, 0), 4, COL_GREEN);
        }

      // save some stats for that location:
       statsFile  <<maxloc.i<<' '<<maxloc.j<<' '<<minloc.i<<' '
                  <<minloc.j<<' '<<ma<<' '<<mi<<' '<<av<<' '<<sdev
                  <<' '<<npeaks<<' '<<peaksum
                  <<" # Xmax Ymax Xmin Ymin max min avg std npeaks peaksum"
                  <<std::endl;

      // build a vector of points where we will save samples. First is
      // the max, second the min, then a bunch of random locations:
      std::vector<Point2D<int> > loc;
      loc.push_back(maxloc);
      loc.push_back(minloc);
      for (uint n = 0; n < 100; n ++)
        loc.push_back(Point2D<int>(randomUpToNotIncluding(input.getWidth()),
                              randomUpToNotIncluding(input.getHeight())));

      // Get all the conspicuity maps:
      ImageSet<float> cmap;
      //LFATAL("FIXME");
      rutz::shared_ptr<SimReqVCXmaps> vcxm(new SimReqVCXmaps(this));
      q->request(vcxm); // VisualCortex is now filling-in the maps...
      rutz::shared_ptr<ChannelMaps> chm = vcxm->channelmaps();
      uint numSubmaps = chm->numSubmaps();
      for(uint i=0;i < numSubmaps; i++)
      {
        NamedImage<float> tempMap = chm->getRawCSmap(i);
        Image<float> m = tempMap;
        cmap.push_back(m);

        // also store sample points at the min/max locations:
        Point2D<int> p; float v;
        findMax(m, p, v); loc.push_back(p);
        findMin(m, p, v); loc.push_back(p);
      }
      /*
      for (uint i = 0; i < itsBrain->getVC()->numChans(); i ++)
        {
          Image<float> m = itsBrain->getVC()->subChan(i)->getOutput();
          cmap.push_back(m);

          // also store sample points at the min/max locations:
          Point2D<int> p; float v;
          findMax(m, p, v); loc.push_back(p);
          findMin(m, p, v); loc.push_back(p);
        }
      */

      // Go over all sample points and save feature map and
      // conspicuity map values at those locations:
      for (uint i = 0; i < loc.size(); i ++)
        {
          Point2D<int> p = loc[i];
          Point2D<int> pp(int(p.i / scale), int(p.j / scale));

           statsFile <<p.i<<' '<<p.j<<"     ";

          // do the conspicuity maps first. Since they are all at the
          // scale of the AGM, we use pp:
          for (uint j = 0; j < cmap.size(); j ++)
          {
            if((int(p.i / scale) < agm.getWidth()) &&
               (int(p.j / scale) < agm.getHeight()))
            {
              (statsFile)<<cmap[j].getVal(pp)<<' ';
              (statsFile)<<"    ";
            }
            else
            {
              (statsFile)<<"-1"<<' ';
              (statsFile)<<"    ";
            }
          }

          // now the feature maps, we use coordinates p:
          /* TOO BOGUS - disabled for now
          std::vector<double> f;
          itsBrain->getVC()->getFeatures(p, f);
          for (uint j = 0; j < f.size(); j ++) (*statsFile)<<f[j]<<' ';
          */

           statsFile  <<"# features "<<i<<" at ("<<p.i
                         <<", "<<p.j<<')'<<std::endl;
        }
  }

  statsFile.flush();
  statsFile.close();
  unlockFile(itsStatsFname.getVal().c_str(),fd,fl);
  // save results?
  if (res.initialized())
    ofs->writeRGB(res, "T",
                  FrameInfo("SimulationViewerStats trajectory", SRC_POS));

  // Should we compute attention gate stats
  // If we have AG stats we will save the basic LAM stats anyways
  if(itsComputeAGStats.getVal())
    computeAGStats(*q);
  else if (SeC<SimEventAttentionGateOutput> ag =
           q->check<SimEventAttentionGateOutput>(this))
    computeLAMStats(ag->lam());

  //! Save the overlap image
  if(itsOverlap.initialized())
    ofs->writeRGB(itsOverlap, "AG-STAT-MASK",
                  FrameInfo("Stats mask overlap", SRC_POS));

  if(itsVisualSegments.initialized())
    ofs->writeRGB(itsVisualSegments, "AG-STAT-SEGS",
                  FrameInfo("Stats segments", SRC_POS));

  if(itsVisualCandidates.initialized())
    ofs->writeGray(itsVisualCandidates, "AG-STAT-CAND",
                   FrameInfo("Stats candidates", SRC_POS));

}
Example #10
0
void PoldiPeakSearch::exec() {
  g_log.information() << "PoldiPeakSearch:" << std::endl;

  Workspace2D_sptr correlationWorkspace = getProperty("InputWorkspace");
  MantidVec correlationQValues = correlationWorkspace->readX(0);
  MantidVec correlatedCounts = correlationWorkspace->readY(0);
  g_log.information() << "   Auto-correlation data read." << std::endl;

  Unit_sptr xUnit = correlationWorkspace->getAxis(0)->unit();

  if (xUnit->caption() == "") {
    g_log.information()
        << "   Workspace does not have unit, defaulting to MomentumTransfer."
        << std::endl;

    xUnit = UnitFactory::Instance().create("MomentumTransfer");
  } else {
    g_log.information() << "   Unit of workspace is " << xUnit->caption() << "."
                        << std::endl;
  }

  setMinimumDistance(getProperty("MinimumPeakSeparation"));
  setMinimumPeakHeight(getProperty("MinimumPeakHeight"));
  setMaximumPeakNumber(getProperty("MaximumPeakNumber"));

  if (m_doubleMinimumDistance > static_cast<int>(correlatedCounts.size())) {
    throw(std::runtime_error("MinimumPeakSeparation is smaller than number of "
                             "spectrum points - no peaks possible."));
  }

  g_log.information() << "   Parameters set." << std::endl;

  MantidVec summedNeighborCounts = getNeighborSums(correlatedCounts);
  g_log.information() << "   Neighboring counts summed, contains "
                      << summedNeighborCounts.size() << " data points."
                      << std::endl;

  std::list<MantidVec::const_iterator> peakPositionsSummed =
      findPeaks(summedNeighborCounts.begin(), summedNeighborCounts.end());
  g_log.information() << "   Peaks detected in summed spectrum: "
                      << peakPositionsSummed.size() << std::endl;

  /* This step is required because peaks are actually searched in the
   * "sum-of-neighbors"-spectrum.
   * The mapping removes the offset from the peak position which results from
   * different beginning
   * of this vector compared to the original correlation counts.
   */
  std::list<MantidVec::const_iterator> peakPositionsCorrelation =
      mapPeakPositionsToCorrelationData(peakPositionsSummed,
                                        summedNeighborCounts.begin(),
                                        correlatedCounts.begin());
  g_log.information() << "   Peak positions transformed to original spectrum."
                      << std::endl;

  /* Since intensities are required for filtering, they are extracted from the
   * original count data,
   * along with the Q-values.
   */
  std::vector<PoldiPeak_sptr> peakCoordinates =
      getPeaks(correlatedCounts.begin(), correlatedCounts.end(),
               peakPositionsCorrelation, correlationQValues, xUnit);
  g_log.information()
      << "   Extracted peak positions in Q and intensity guesses." << std::endl;

  UncertainValue backgroundWithSigma =
      getBackgroundWithSigma(peakPositionsCorrelation, correlatedCounts);
  g_log.information() << "   Calculated average background and deviation: "
                      << UncertainValueIO::toString(backgroundWithSigma)
                      << std::endl;

  if ((*getProperty("MinimumPeakHeight")).isDefault()) {
    setMinimumPeakHeight(minimumPeakHeightFromBackground(backgroundWithSigma));
  }

  std::vector<PoldiPeak_sptr> intensityFilteredPeaks(peakCoordinates.size());
  auto newEnd = std::remove_copy_if(
      peakCoordinates.begin(), peakCoordinates.end(),
      intensityFilteredPeaks.begin(),
      boost::bind(&PoldiPeakSearch::isLessThanMinimum, this, _1));
  intensityFilteredPeaks.resize(
      std::distance(intensityFilteredPeaks.begin(), newEnd));

  g_log.information() << "   Peaks above minimum intensity ("
                      << m_minimumPeakHeight
                      << "): " << intensityFilteredPeaks.size() << std::endl;

  std::sort(intensityFilteredPeaks.begin(), intensityFilteredPeaks.end(),
            boost::bind<bool>(&PoldiPeak::greaterThan, _1, _2,
                              &PoldiPeak::intensity));

  for (std::vector<PoldiPeak_sptr>::const_iterator peak =
           intensityFilteredPeaks.begin();
       peak != intensityFilteredPeaks.end(); ++peak) {
    m_peaks->addPeak(*peak);
  }

  /* The derived background error is set as error in the workspace containing
   * correlation data, so it may be used as weights for peak fitting later on.
   */
  setErrorsOnWorkspace(correlationWorkspace, backgroundWithSigma.error());

  setProperty("OutputWorkspace", m_peaks->asTableWorkspace());
}
void SimplePeakFinder::findPeaks(const std::vector< std::vector<double> >& signal, std::vector< std::vector<unsigned int> >& indexes) const{
    indexes.resize(signal.size());
    for (unsigned int i = 0; i < signal.size(); i++){
	findPeaks(signal[i], indexes[i]);
    }
}
Example #12
0
    int main(int argc, char **argv) {


        if (argc != 4) {
            exit_with_help();
        }

        LOGD( "start to get feature of audio file" );

        FILE *soundfile = NULL;
        FILE *chirpfile = NULL;
        FILE *featurefile = NULL;
        char *sound_filename = NULL;
        char *chirp_filename = NULL;
        char *feature_filename = NULL;
        sound_filename = argv[1];
        chirp_filename = argv[2];
        feature_filename = argv[3];

        int numSample = 0;
        int rawaudioSignals[200000];
        int value;


        int i2 = 0;
        float chirp[301];
        float chirp_value;

        if (sound_filename) {
            soundfile = fopen(sound_filename, "r");
            if (soundfile == NULL) {
                fprintf(stderr, "can't open file %s\n", sound_filename);
                exit(1);
            }
        }

        while (fscanf(soundfile, "%d", &value) > 0) {
            rawaudioSignals[numSample] = value;
            numSample++;
            if (numSample == 199998) {
                break;
            }
        }

        if (chirp_filename) {
            chirpfile = fopen(chirp_filename, "r");
            if (chirpfile == NULL) {
                fprintf(stderr, "can't open file %s\n", chirp_filename);
                exit(1);
            }
        }

        while (fscanf(chirpfile, "%f", &chirp_value) > 0) {
            chirp[i2] = chirp_value;
            i2++;
        }


        double *audio_signal = (double *) malloc(numSample * sizeof(double));
        if (audio_signal == NULL) {
            /* we have a problem */
            fprintf(stderr, "Error: out of memory.\n");
            return 1;
        }


        for (int j = 0; j < numSample; j++) {
            audio_signal[j] = (double) rawaudioSignals[j];
        }

        double *match_signal = (double *) malloc(numSample * sizeof(double));
        if (match_signal == NULL) {
            /* we have a problem */
            fprintf(stderr, "Error: out of memory.\n");
            return 1;
        }


        Dsp::SimpleFilter<Dsp::Butterworth::BandPass<5>, 1> f;
        f.setup(5,    // order
                48000,// sample rate
                15000, // center frequency
                3000);  // band width);
        f.process(numSample, &audio_signal);

//    FILE *outf_filter = fopen("filter1_0403_test2.txt", "w");
//
//    for ( int j=0; j<numSample; j++ )
//    {
//        //printf("%f\n", audio_signal[j]);
//        fprintf(outf_filter, "%f  ", audio_signal[j]);
//    }



        convCalculate(chirp, audio_signal, match_signal, numSample);

        FILE *outf_conv = fopen("convert1_0403_22_sound11.txt", "w");

//        for (int j = 0; j < numSample; j++) {
//            //printf("%f\n", audio_signal[j]);
//            fprintf(outf_conv, "%f  ", match_signal[j]);
//        }


//        printf("%d\n", numSample);

//    FILE *outf = fopen("results1_0307_test2.txt", "w");
//
//    for ( int j=0; j<numSample; j++ )
//    {
//        //printf("%f\n", audio_signal[j]);
//        fprintf(outf, "%f  ", audio_signal[j]);
//    }

        int duration1 = 2300;
        int duration2 = 2000;
        int f_start = 600;
        int f_end = 1500;
        int focus_duration = 900;
        int step = 100;
        int peak_threshold = 200;
        int threshold = 200000;
        int threshold2 = 2000000;

        double tmp_whole_max = 0;
        int tmp_whole_max_index = 0;

        double tmp_echo_max = 0;
        int tmp_echo_max_index = 0;

        double tmp_max = 0;
        int tmp_max_index = 0;

        double tmp_exceed_threshold = 0;
        int tmp_exceed_index = 0;

        int focus_start_list[10];
        int focus_end_list[10];
        int focus_count = 0;

        int whole_start = 0;


        tmp_whole_max_index = findMaximum(&match_signal[0], whole_start, numSample, tmp_whole_max);
//    printf("%d\n", tmp_whole_max_index);
//    printf("%f\n", tmp_whole_max);

        while (tmp_whole_max > threshold) {

            tmp_exceed_index = ExceedThreshold(&match_signal[0], whole_start, numSample, threshold,
                                               tmp_exceed_threshold);
//            printf("process raw sound file  %s\n", sound_filename);
//            printf("tmp_exceed_index  %d\n", tmp_exceed_index);
//            printf("tmp_whole_max  %f\n", tmp_whole_max);

            int tmp_start = tmp_exceed_index;
            int tmp_end = tmp_exceed_index + duration1;
            whole_start = tmp_end;
//            printf("whole_start  %d\n", whole_start);
            if ((tmp_start < 0) | (tmp_end > numSample)) {

                break;
            }
            tmp_max_index = findMaximum(&match_signal[0], tmp_start, tmp_end, tmp_max);
//            printf("tmp_max_index  %d\n", tmp_max_index);
//            printf("tmp_max  %f\n", tmp_max);


            int tmp_end2 = tmp_max_index + duration2;

            tmp_echo_max_index = findMaximum(&match_signal[0], (tmp_max_index + f_start), (tmp_max_index + f_end),
                                             tmp_echo_max);

            if ((tmp_end2 > tmp_end) || (tmp_echo_max > threshold2)) {
                tmp_whole_max_index = findMaximum(&match_signal[0], whole_start, numSample, tmp_whole_max);
                continue;
            }
            focus_start_list[focus_count] = tmp_max_index + f_start;
            focus_end_list[focus_count] = tmp_max_index + f_end;
            focus_count = focus_count + 1;


            tmp_whole_max_index = findMaximum(&match_signal[0], whole_start, numSample, tmp_whole_max);

        }

//        for (int i = 0; i < focus_count; i++) {
//            printf("%d\t", focus_start_list[i]);
//            printf("%d\n", focus_end_list[i]);
//
//        }

        double *ave_focus = (double *) malloc(focus_duration * sizeof(double));
        if (ave_focus == NULL) {
            /* we have a problem */
            printf("Error: out of memory.\n");
            return 1;
        }

        average(&match_signal[0], &focus_start_list[0], focus_count, focus_duration, &ave_focus[0]);

        double Energy = getEnergy(&ave_focus[0], focus_duration);

        int numPeaks = 0;
        numPeaks = findPeaks(&ave_focus[0], focus_duration, peak_threshold);
//        printf("\n\n%d\n", numPeaks);

        double mean_var = 0.0;
        double max_var = 0.0;

        getVarResult(&ave_focus[0], focus_duration, step, mean_var, max_var);
//        printf("%f\n", mean_var);
//        printf("%f\n", max_var);


        if (feature_filename) {
            featurefile = fopen(feature_filename, "w");
            if (featurefile == NULL) {
                fprintf(stderr, "can't open file %s\n", feature_filename);
                exit(1);
            }
        }


        fprintf(featurefile, "0 ");
        fprintf(featurefile, "1:%f ", Energy);
        fprintf(featurefile, "2:%d ", numPeaks);
        fprintf(featurefile, "3:%f ", mean_var);
        fprintf(featurefile, "4:%f\n", max_var);


//        printf("finish raw sound file  %s\n", sound_filename);

        free(audio_signal);
        free(match_signal);
        free(ave_focus);
//    fclose(outf);
//    fclose(outf_conv);
        fclose(soundfile);
        fclose(chirpfile);
        fclose(featurefile);

        return 0;


    }