////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// generate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RawPcmData::Ptr AdditiveSynthesizer::generate( size_t length )
{
   RawPcmData* result = new RawPcmData( getSamplingInfo(), length );

   const std::vector< HarmonicInfo >& harmonicsInfo = getHarmonicsInfo();
   assert( harmonicsInfo.size() > 0 );

   std::vector< double > phase( harmonicsInfo.size() );
   for ( size_t iHarmonic = 0; iHarmonic < harmonicsInfo.size(); ++iHarmonic )
   {
      phase[ iHarmonic ] = harmonicsInfo[ iHarmonic ].getPhase();
   }

   for ( size_t iSample = 0; iSample < length; ++iSample )
   {
      double val = 0;
      for ( size_t iHarmonic = 0; iHarmonic < harmonicsInfo.size(); ++iHarmonic )
      {
         phase[ iHarmonic ] += harmonicsInfo[ iHarmonic ].getPhaseStep();
         val += harmonicsInfo[ iHarmonic ].getAmplitude() * sin( phase[ iHarmonic ] );
      }
      (*result)[ iSample ] = val * getCurrentSampleAmplitude();
      nextSample();
   }

   setPhase( fmod( phase[ 0 ], 2 * M_PI ) );

   return RawPcmData::Ptr( result );
}
Example #2
0
double *readSample(FILE* file, int chunkSize, int sampleSize, int numChan)
{
    double *result;
    double *dst;
    int i, size;

    size = chunkSize / (numChan * sampleSize);
    result = malloc(size * sizeof(double));

    dst = result;
    for(i = 0; i < size; i++)
        *dst++ = nextSample(file, sampleSize, numChan);

    return result;
}
Example #3
0
/*
From Lynn 2nd ed pg 20
x[n] = sin(n * 2 * Pi * f / fs)
f = desired frequency
fs = sampling frequency or 1/sample rate

We calculate 2Pif/fs once and save it as step
so
x[n] = sin(n * stepTone)
----------------
The number of samples per cycle is fixed, but the samples will be taken at different points in
each cycle.  We need to make sure that the spacing between each sample is consistent with the
sample rate and frequency.
A 10hz signal completes a full cycle ever 1/10 sec (1/Freg)
At 48000 sps, this means we need 4800 samples for a complete cytle (sampleRate / freq)
So a 24khz signal will have 2 samples per cycle (48000/24000), which is the Nyquist limit
-----------------
*/
void NCO::genSingle(CPX *_in, quint32 _numSamples, double _dbGain, bool _mix)
{
	CPX cpx;
	for (quint32 i = 0; i < _numSamples; i++) {
		nextSample(cpx);
		cpx.real(cpx.real() * _dbGain);
		cpx.imag(cpx.imag() * _dbGain);
		if (_mix) {
			_in[i].real(_in[i].real() + cpx.real());
			_in[i].imag(_in[i].imag() + cpx.imag());
		} else {
			_in[i].real(cpx.real());
			_in[i].imag(cpx.imag());
		}
	}

}
Example #4
0
AfarasView::AfarasView(QWidget *parent, Qt::WFlags flags) : KXmlGuiWindow(parent, flags),
  recorder(0),
  currentIndex(0)
{
  KGlobal::locale()->insertCatalog("simonlib");
  ui.setupUi(this);

  connect(ui.pbStartReview, SIGNAL(clicked()), this, SLOT(start()));
  connect(ui.pbBlacklistSample, SIGNAL(toggled(bool)), this, SLOT(blackListSample(bool)));
  connect(ui.pbPreviousSample, SIGNAL(clicked()), this, SLOT(previousSample()));
  connect(ui.pbNextSample, SIGNAL(clicked()), this, SLOT(nextSample()));
  connect(ui.pbBack, SIGNAL(clicked()), this, SLOT(stop()));

  connect(ui.urInputPrompts, SIGNAL(textChanged(QString)), this, SLOT(inputFilesChanged()));
  connect(ui.urPathPrefix, SIGNAL(textChanged(QString)), this, SLOT(inputFilesChanged()));
  connect(ui.urOutputBlacklist, SIGNAL(textChanged(QString)), this, SLOT(inputFilesChanged()));

  ui.wgRecording->setLayout(new QVBoxLayout());

  KStandardAction::quit(this, SLOT(close()), actionCollection());
  KStandardAction::preferences(this, SLOT(showConfig()), actionCollection());
  setupGUI();
}
// Sample singly connected segment. Returns false if end_ reached.
bool Foam::uniformSet::trackToBoundary
(
    Particle<passiveParticle>& singleParticle,
    point& samplePt,
    label& sampleI,
    DynamicList<point>& samplingPts,
    dynamicLabelList& samplingCells,
    dynamicLabelList& samplingFaces,
    DynamicList<scalar>& samplingCurveDist
) const
{
    // distance vector between sampling points
    const vector offset = (end_ - start_)/(nPoints_ - 1);
    const vector smallVec = tol*offset;
    const scalar smallDist = mag(smallVec);

    // Alias
    const point& trackPt = singleParticle.position();

    while(true)
    {
        // Find next samplePt on/after trackPt. Update samplePt, sampleI
        if (!nextSample(trackPt, offset, smallDist, samplePt, sampleI))
        {
            // no more samples.
            if (debug)
            {
                Info<< "trackToBoundary : Reached end : samplePt now:"
                    << samplePt << "  sampleI now:" << sampleI << endl;
            }
            return false;
        }

        if (mag(samplePt - trackPt) < smallDist)
        {
            // trackPt corresponds with samplePt. Store and use next samplePt
            if (debug)
            {
                Info<< "trackToBoundary : samplePt corresponds to trackPt : "
                    << "  trackPt:" << trackPt << "  samplePt:" << samplePt
                    << endl;
            }

            samplingPts.append(trackPt);
            samplingCells.append(singleParticle.cell());
            samplingFaces.append(-1);
            samplingCurveDist.append(mag(trackPt - start_));

            // go to next samplePt
            if (!nextSample(trackPt, offset, smallDist, samplePt, sampleI))
            {
                // no more samples.
                if (debug)
                {
                    Info<< "trackToBoundary : Reached end : "
                        << "  samplePt now:" << samplePt
                        << "  sampleI now:" << sampleI
                        << endl;
                }

                return false;
            }
        }


        if (debug)
        {
            Info<< "Searching along trajectory from "
                << "  trackPt:" << trackPt
                << "  trackCellI:" << singleParticle.cell()
                << "  to:" << samplePt << endl;
        }

        point oldPos = trackPt;
        label facei = -1;
        do
        {
            singleParticle.stepFraction() = 0;
            singleParticle.track(samplePt);

            if (debug)
            {
                Info<< "Result of tracking "
                    << "  trackPt:" << trackPt
                    << "  trackCellI:" << singleParticle.cell()
                    << "  trackFaceI:" << singleParticle.face()
                    << "  onBoundary:" << singleParticle.onBoundary()
                    << "  samplePt:" << samplePt
                    << "  smallDist:" << smallDist
                    << endl;
            }
        }
        while
        (
            !singleParticle.onBoundary()
         && (mag(trackPt - oldPos) < smallDist)
        );

        if (singleParticle.onBoundary())
        {
            //Info<< "trackToBoundary : reached boundary" << endl;
            if (mag(trackPt - samplePt) < smallDist)
            {
                //Info<< "trackToBoundary : boundary is also sampling point"
                //    << endl;
                // Reached samplePt on boundary
                samplingPts.append(trackPt);
                samplingCells.append(singleParticle.cell());
                samplingFaces.append(facei);
                samplingCurveDist.append(mag(trackPt - start_));
            }

            return true;
        }

        //Info<< "trackToBoundary : reached internal sampling point" << endl;
        // Reached samplePt in cell or on internal face
        samplingPts.append(trackPt);
        samplingCells.append(singleParticle.cell());
        samplingFaces.append(-1);
        samplingCurveDist.append(mag(trackPt - start_));

        // go to next samplePt
    }
}
Example #6
0
int main(int argc, char *argv[ ])
{
    FILE *infile, *outfile;
    char prefix[4];
    char fileFormat[4];
    char ckID[4];
    unsigned long nChunkSize;
    short wFormatTag;
    short nChannels;
    unsigned long nSamplesPerSecond;
    unsigned long nBytesPerSecond;
    unsigned long nOutputSamplesPerSecond;
    short nBlockAlign;
    short nBitsPerSample;
    int i, j;

    if (argc < 3)
    {
        printf("Usage: wav2raw sourceWavFile destRawFile <outRate>\n");
        printf("Output rate is given in Hand should be <= to the input sample sample.\n");
        printf("Success returns errorlevel 0. Error return greater than zero.\n");
        printf("\n");
        printf("Ex: wav2raw input.wav output.raw 11025\n");
        exit(1);
    }

    /* Open source for binary read (will fail if file does not exist) */
    if ((infile = fopen( argv[1], "rb" )) == NULL)
//    if ((infile = fopen( "test.wav", "rb" )) == NULL)
    {
        printf("The source file %s was not opened\n", argv[1]);
        exit(2);
    }

    if (argc > 3)
        nOutputSamplesPerSecond = atoi(argv[3]);
    else
        nOutputSamplesPerSecond = 0;

    /* Read the header bytes. */
    fscanf( infile, "%4s", prefix );
    fscanf( infile, "%4c", &nChunkSize );
    fscanf( infile, "%4c", fileFormat );
    fscanf( infile, "%4c", ckID );
    fscanf( infile, "%4c", &nChunkSize );
    fscanf( infile, "%2c", &wFormatTag );
    fscanf( infile, "%2c", &nChannels );
    fscanf( infile, "%4c", &nSamplesPerSecond );
    fscanf( infile, "%4c", &nBytesPerSecond );
    fscanf( infile, "%2c", &nBlockAlign );
    fscanf( infile, "%2c", &nBitsPerSample );

    // pass extra bytes in bloc
    for(i = 0; i < nChunkSize - 0x10; i++)
        fscanf( infile, "%1c", &j);

    fscanf( infile, "%4c", ckID );
    fscanf( infile, "%4c", &nChunkSize );

    if (nOutputSamplesPerSecond == 0)
        nOutputSamplesPerSecond = nSamplesPerSecond;

    if(nSamplesPerSecond < nOutputSamplesPerSecond)
    {
        printf("Output rate (%ld) cannot be above input rate (%ld)\n", nOutputSamplesPerSecond, nSamplesPerSecond);
        printf("Use lower output rate value or higher input rate file\n");
        exit(4);
    }

        /* Open output for write */
    if( (outfile = fopen( argv[2], "w" )) == NULL )
//    if( (outfile = fopen( "out.raw", "w" )) == NULL )
    {
        printf("The output file %s was not opened\n", argv[2]);
        exit(3);
    }

    int nBytesPerSample = nBitsPerSample / 8;
    int size = nChunkSize / (nChannels * nBytesPerSample);
    double offset;
    double step;
    double value;
    double lastSample;

    step = nSamplesPerSecond;
    step /= nOutputSamplesPerSecond;
    value = 0;
    lastSample = 0;

    for(offset = 0; offset < size; offset += step)
    {
        char byte;
        double sample = 0;

        if (value < 0) sample += lastSample * -value;

        value += step;

        while(value > 0)
        {
            lastSample = nextSample(infile, nBytesPerSample, nChannels);

            if (value >= 1)
                sample += lastSample;
            else
                sample += lastSample * value;

            value--;
        }

        sample /= step;
        byte = round(sample);

        fwrite(&byte, 1, 1, outfile);
    }

    fclose(infile);
    fclose(outfile);

    return 0;
}
Example #7
0
void handleKeyboard(int key) {

    char cKey = (char)key;

    // ESC
	if(cKey == 27) {
		b_running = false;
        return;
	}


    // toggle mode
    if(cKey == 'm') {

        mode = (mode + 1) % 2;

        std::stringstream ss;
        ss << "mode: " << (mode == MODE_SAMPLES ? "samples" : "glint");
        animator.setText(ss.str());

        return;

    }


    if(cKey == 'd') { // delete sample

        deleteSample();
        bUpdateGraphics = true;

    }


    // see which mode
    if(mode == MODE_SAMPLES) {

        if(cKey == 'S') { // right arrow

            nextSample();
            bUpdateGraphics = true;

        }
        else if(cKey == 'Q') { // left arrow

            prevSample();
            bUpdateGraphics = true;

        }
        else if(cKey == 'R') { // up arrow

            nextContainer();
            bUpdateGraphics = true;

        }
        else if(cKey == 'T') { // down arrow

            prevContainer();
            bUpdateGraphics = true;

        }

    }
    else if(mode == MODE_GLINT) {

        calib::LEDCalibSample &sample = LEDContainers[indContainer].getSamples()[indSample];

        if(cKey == 'S') { // right arrow

            int sugg = sample.glint.x + 1;
            if(sugg < 640) {
                sample.glint.x = sugg;
            }

            bUpdateGraphics = true;

        }
        else if(cKey == 'Q') { // left arrow

            int sugg = sample.glint.x - 1;
            if(sugg >= 0) {
                sample.glint.x = sugg;
            }

            bUpdateGraphics = true;

        }
        else if(cKey == 'R') { // up arrow

            int sugg = sample.glint.y - 1;
            if(sugg >= 0) {
                sample.glint.y = sugg;
            }

            bUpdateGraphics = true;

        }
        else if(cKey == 'T') { // down arrow

            int sugg = sample.glint.y + 1;
            if(sugg < 480) {
                sample.glint.y = sugg;
            }

            bUpdateGraphics = true;

        }


    }

}
Example #8
0
int Caller::loadEntries( const std::string path)
{
	std::string nextLine;
	std::string key;
	std::string chr;
	std::string refBase;
	int readDepth;
	int pos;

	// Open the sample file
	std::ifstream inputFile( path.c_str());
	if( !inputFile.is_open())
	{
		perror( "Error opening input readcount file");
		exit( 1);
	}

	// For each line in the sample file (which will correspond to a genomic location)
	while( std::getline( inputFile, nextLine))
	{
		// Split the line into tokens separated by whitespace (for columns, since this is a tab delimited file)
		std::istringstream strStream( nextLine);
		std::istream_iterator<std::string> begin( strStream), end;
		std::vector<std::string> stringTokens( begin, end);

		// Get all main fields
		chr = stringTokens[0];
		pos = atoi( stringTokens[1].c_str());
		refBase = stringTokens[2];
		refBase[0] = toupper( refBase[0]);
		readDepth = atoi( stringTokens[3].c_str());

		// Generate the key, (chr:pos)
		key = stringTokens[0] + ":" + stringTokens[1];
		if( key == "")
		{
			std::cout << "Empty key" << std::endl;
		}

		// Create the base ReadcountEntry object
		ReadcountEntry nextReadcountEntry( refBase, readDepth);

		// Get all subfields for each allele, the 5th column (stringTokens[4]) is garbage due to a bug with the bam-readcount program, ignore it
		for( int i = 5; i < stringTokens.size(); i++)
		{
			std::vector<std::string> nextSubTokens = Common::split( stringTokens[i], ":", true);

			// Create the Allele objects and add them to the current ReadcountEntry object
			std::string base = nextSubTokens[0];
			int count = atoi( nextSubTokens[1].c_str());
			double avgMappingQuality = atof( nextSubTokens[2].c_str());
			double avgBaseQuality = atof( nextSubTokens[3].c_str());
			double avgSEMappingQuality = atof( nextSubTokens[4].c_str());
			int numPlusStrand = atoi( nextSubTokens[5].c_str());
			int numMinusStrand = atoi( nextSubTokens[6].c_str());
			double avgPosAsFraction = atof( nextSubTokens[7].c_str());
			double avgNumMismatchesAsFraction = atof( nextSubTokens[8].c_str());
			double avgSumMismatchQualities = atof( nextSubTokens[9].c_str());
			int numQ2ContainingReads = atoi( nextSubTokens[10].c_str());
			double avgDistanceToQ2StartInQ2Reads = atof( nextSubTokens[11].c_str());
			double avgClippedLength = atof( nextSubTokens[12].c_str());
			double avgDistanceToEffective3pEnd = atof( nextSubTokens[13].c_str());

			bool variant = false;
			if( base != refBase)
			{
				variant = true;
			}

			double percentage;
			if( readDepth != 0)
			{
				percentage = ( double) count / ( double) readDepth * 100;
			}
			else
			{
				percentage = 0;
			}

			Allele nextAllele( base, count, avgMappingQuality, avgBaseQuality, avgSEMappingQuality, numPlusStrand, numMinusStrand,
							   avgPosAsFraction, avgNumMismatchesAsFraction, avgSumMismatchQualities, numQ2ContainingReads,
							   avgDistanceToQ2StartInQ2Reads, avgClippedLength, avgDistanceToEffective3pEnd, percentage, variant);

			nextReadcountEntry.addAllele( nextAllele);
		}

		// Now, the ReadcountEntry object is filled, so we can create the Sample object
		nextReadcountEntry.setMostFreqVariantAllele();
		Sample nextSample( path, nextReadcountEntry);

		// Finally, add the Sample object to the Location object,
		// Check if the Location object with the current key exists in the hash table
		std::unordered_map<std::string, Location>::iterator iter = locationTable.find( key);
		if( iter == locationTable.end())
		{
			// If it does not exist, create the Location object
			Location newLocation( chr, pos);

			// Add the new Sample to the Location object
			newLocation.addSample( nextSample);

			// Insert the new key-Location pair to the hash table
			std::pair<std::string, Location> newKeyPair( key, newLocation);
			locationTable.insert( newKeyPair);
		}
		else
		{
			bool sampleExists = false;
			std::vector<Sample> samples = ( iter->second).getSamples();
			for( int j = 0; j < samples.size(); j++)
			{
				if( samples[j].getSampleName() == nextSample.getSampleName())
				{
					sampleExists = true;
				}
			}

			if( !sampleExists)
			{
				( iter->second).addSample( nextSample);
			}
		}
	}

	// Check if the file was read correctly
	if( inputFile.bad())
	{
		perror( "Error reading input readcount file");
	}

	// Close the input sample file
	inputFile.close();
}
Example #9
0
 unsigned long SimpleRandom::next(const unsigned long exclusiveMaximum) {
     return nextSample() % exclusiveMaximum;
 }