Exemplo n.º 1
0
 spectrum& spectrum::operator*=(const spectrum& other) {
     assert(channels == other.channels);
     assert(samples() == other.samples());
     for(int i = 0; i < channels; i++)
         for(int j = 0; j < samples(); j++)
             data[i][j] *= other[i][j];
     return *this;
 }
Exemplo n.º 2
0
 Real IncrementalStatistics::variance() const {
     QL_REQUIRE(weightSum() > 0.0, "sampleWeight_= 0, unsufficient");
     QL_REQUIRE(samples() > 1, "sample number <= 1, unsufficient");
     Real n = static_cast<Real>(samples());
     return n / (n - 1.0) *
            boost::accumulators::extract_result<
                boost::accumulators::tag::weighted_variance>(acc_);
 }
Exemplo n.º 3
0
 Real IncrementalStatistics::skewness() const {
     QL_REQUIRE(samples() > 2, "sample number <= 2, unsufficient");
     Real n = static_cast<Real>(samples());
     Real r1 = n / (n - 2.0);
     Real r2 = (n - 1.0) / (n - 2.0);
     return std::sqrt(r1 * r2) * 
            boost::accumulators::extract_result<
                boost::accumulators::tag::weighted_skewness>(acc_);
 }
Exemplo n.º 4
0
 std::complex<double> spectrum::dot(const spectrum& other) const {
     assert(channels == other.channels);
     assert(samples() == other.samples());
     std::complex<double> result(0, 0);
     for(int i = 0; i < channels; i++)
         for(int j = 0; j < samples(); j++)
             result += data[i][j] * conj(other[i][j]);
     return result;
 }
Exemplo n.º 5
0
	void Audio::setLoop(const Arg::loopBegin_<uint64> loopBegin)
	{
		assert(*loopBegin < samples());

		const uint64 loopBeginSample = *loopBegin;
		const uint64 loopEndSample = samples() - 1;

		Siv3DEngine::GetAudio()->setLoop(
			m_handle->id(),
			true,
			loopBeginSample,
			loopEndSample);
	}
Exemplo n.º 6
0
 size_t signal::find(const signal& sig, double threshold) const {
     // Sanity check signal compatibility
     assert(channels == sig.channels);
     // Ensure that the input signal is not larger than this signal
     if(sig.samples() > samples()) return npos;
     // Search for the signal
     size_t n = samples() - sig.samples();
     for(size_t i = 0; i <= n; i++) {
         signal window(slice(i, i + sig.samples()));
         double corr = std::abs(sig.correlation(window));
         if(corr >= threshold) return i;
     }
     // Signal not found
     return npos;
 }
Exemplo n.º 7
0
 Real IncrementalStatistics::kurtosis() const {
     QL_REQUIRE(samples() > 3,
                "sample number <= 3, unsufficient");
     boost::accumulators::extract_result<
         boost::accumulators::tag::weighted_kurtosis>(acc_);
     Real n = static_cast<Real>(samples());
     Real r1 = (n - 1.0) / (n - 2.0);
     Real r2 = (n + 1.0) / (n - 3.0);
     Real r3 = (n - 1.0) / (n - 3.0);
     return ((3.0 + boost::accumulators::extract_result<
                        boost::accumulators::tag::weighted_kurtosis>(acc_)) *
                 r2 -
             3.0 * r3) *
            r1;
 }
Exemplo n.º 8
0
sp_mat make_sample_basis(uint N,
                        uint K){
  sp_mat basis = sp_mat(N,K);
  set<uword> keys;
  uvec samples = randi<uvec>(K,distr_param(0,N-1));
  for(uint k = 0; k < K; k++){
    while(keys.count(samples(k)) > 0){
      samples(k) = randi<uvec>(1,distr_param(0,N-1))(0);
    }
    basis(samples(k),k) = 1;
    keys.insert(samples(k));
  }
  assert(K == accu(basis));
  return basis; // Should be orthonormal by default
}
void DemoQNanoItemPainter::drawGraphBars(float x, float y, float w, float h, int items, float t) {

    QVarLengthArray<float, 1024> samples(items);
    QVarLengthArray<float, 1024> sx(items); QVarLengthArray<float, 1024> sy(items);
    float dx = w/(items-1);
    float barWidth = dx * 0.8;
    float margin = dx - barWidth;
    int i;

    // Generate positions
    for (i = 0; i<items; i++) {
        samples[i] = 0.5 + sinf(i*0.1+t)*0.5;
    }
    for (i = 0; i < items; i++) {
        sx[i] = x+i*dx + margin/2;
        sy[i] = h*samples[i];
    }

    // Draw graph bars
    m_painter->beginPath();
    for (i = 0; i < items; i++) {
        m_painter->rect((int)sx[i]+0.5, (int)y+1.5, (int)barWidth, (int)sy[i]);
    }
    qreal lineWidth = 0.5 + w * 0.002;
    m_painter->setLineWidth(lineWidth);
    m_painter->setLineJoin(QNanoPainter::JOIN_MITER);
    m_painter->setFillStyle(m_color3);
    m_painter->setStrokeStyle(m_colorBlack);
    m_painter->fill();
    m_painter->stroke();
}
void BladeRfTxComponent::process()
{
    //Get a DataSet from the input DataBuffer
    DataSet< complex<float> >* readDataSet = NULL;
    inBuf_->getReadData(readDataSet);

    // Check if we have to append dummy frames, samps must be multiple of 1024
    size_t size = readDataSet->data.size();
    if (size % BLADERF_SAMPLE_BLOCK_SIZE != 0) {
        int num_samps_to_append = BLADERF_SAMPLE_BLOCK_SIZE - (size % BLADERF_SAMPLE_BLOCK_SIZE);
        std::vector<std::complex<float> > samples(num_samps_to_append, std::complex<float>(0.0, 0.0));
        readDataSet->data.insert(readDataSet->data.end(), samples.begin(), samples.end());
        size += num_samps_to_append;
    }

    // Adjust raw buffer if needed
    if (rawSampleBuffer_.data.capacity() < size) rawSampleBuffer_.data.resize(size);

    // convert samples to bladeRF format
    for (int i = 0; i < size; i++) {
        rawSampleBuffer_.data[i].real(0xa000 | (int16_t)((readDataSet->data[i].real()) * 2000));
        rawSampleBuffer_.data[i].imag(0x5000 | (int16_t)((readDataSet->data[i].imag()) * 2000));
    }

    // Write samples to device
    int ret = bladerf_sync_tx(device_, &(rawSampleBuffer_.data.front()), size, NULL, BLADERF_SYNC_TIMEOUT_MS);
    if (ret != 0) {
        throw IrisException("Failed to send samples to device!");
        LOG(LERROR) << bladerf_strerror(ret);
    }

    //Release the DataSet
    inBuf_->releaseReadData(readDataSet);
}
Exemplo n.º 11
0
 Real GeneralStatistics::mean() const {
     Size N = samples();
     QL_REQUIRE(N != 0, "empty sample set");
     // eat our own dog food
     return expectationValue(identity<Real>(),
                             everywhere()).first;
 }
Exemplo n.º 12
0
void AudioBuffer::apply_f32(std::function<float(float)> _fn)
{
	float *data = &at<float>(0);
	for(unsigned i=0; i<samples(); ++i) {
		data[i] = _fn(data[i]);
	}
}
Exemplo n.º 13
0
void AudioBuffer::apply_u8(std::function<float(float)> _fn)
{
	for(unsigned i=0; i<samples(); ++i) {
		float result = _fn(u8_to_f32(m_data[i]));
		m_data[i] = f32_to_u8(result);
	}
}
Exemplo n.º 14
0
long long
hokuyo::Laser::calcLatency(bool intensity, double min_ang, double max_ang, int clustering, int skip, int num, int timeout)
{
    offset_ = 0;
    if (!portOpen())
        HOKUYO_EXCEPT(hokuyo::Exception, "Port not open.");

    if (num <= 0)
        num = 10;

    int ckreps = 1;
    int scanreps = 1;
    long long int start = getHokuyoClockOffset(ckreps, timeout);
    long long int pre = 0;
    std::vector<long long int> samples(num);
    for (int i = 0; i < num; i++)
    {
        long long int scan = getHokuyoScanStampToSystemStampOffset(intensity, min_ang, max_ang, clustering, skip, scanreps, timeout) - start;
        long long int post = getHokuyoClockOffset(ckreps, timeout) - start;
        samples[i] = scan - (post+pre)/2;
        //printf("%lli %lli %lli %lli %lli\n", samples[i], post, pre, scan, pre - post);
        //fflush(stdout);
        pre = post;
    }

    offset_ = median(samples);
    //printf("%lli\n", median(samples));
    return offset_;
}
Exemplo n.º 15
0
bool SND_In_File::read(vec &v)
{
  if (!good())
    return false;

  int i, n;

  n = samples();
  v.set_size(n, false);
  seek_read(0);

  bool switch_endian = !is_bigendian(); // if LITTLE_ENDIAN than switch
  switch (header.encoding) {
  case enc_linear8 :
    for (i = 0; i < n; i++)
      v(i) = read_endian<char>(file, switch_endian) / 128.0;
    break;
  case enc_linear16 :
    for (i = 0; i < n; i++)
      v(i) = read_endian<short>(file, switch_endian) / 32768.0;
    break;
  case enc_float :
    for (i = 0; i < n; i++)
      v(i) = read_endian<float>(file, switch_endian);
    break;
  case enc_double :
    for (i = 0; i < n; i++)
      v(i) = read_endian<double>(file, switch_endian);
    break;
  default :
    it_warning("SND_In_File::read(): Unsupported encoding!");
    return false;
  }
  return file.good();
}
Exemplo n.º 16
0
static gl::TextureCaps GenerateTextureFormatCaps(const FunctionsGL *functions, GLenum internalFormat)
{
    gl::TextureCaps textureCaps;

    const nativegl::InternalFormat &formatInfo = nativegl::GetInternalFormatInfo(internalFormat, functions->standard);
    textureCaps.texturable = MeetsRequirements(functions, formatInfo.texture);
    textureCaps.filterable = textureCaps.texturable && MeetsRequirements(functions, formatInfo.filter);
    textureCaps.renderable = MeetsRequirements(functions, formatInfo.framebufferAttachment);

    // glGetInternalformativ is not available until version 4.2 but may be available through the 3.0
    // extension GL_ARB_internalformat_query
    if (textureCaps.renderable && functions->getInternalformativ)
    {
        GLint numSamples = 0;
        functions->getInternalformativ(GL_RENDERBUFFER, internalFormat, GL_NUM_SAMPLE_COUNTS, 1, &numSamples);

        if (numSamples > 0)
        {
            std::vector<GLint> samples(numSamples);
            functions->getInternalformativ(GL_RENDERBUFFER, internalFormat, GL_SAMPLES,
                                           static_cast<GLsizei>(samples.size()), &samples[0]);
            for (size_t sampleIndex = 0; sampleIndex < samples.size(); sampleIndex++)
            {
                textureCaps.sampleCounts.insert(samples[sampleIndex]);
            }
        }
    }

    return textureCaps;
}
Exemplo n.º 17
0
TEST(DISABLED_ML_SVM, linear_save_load)
{
    Ptr<cv::ml::SVM> svm1, svm2, svm3;

    svm1 = Algorithm::load<SVM>("SVM45_X_38-1.xml");
    svm2 = Algorithm::load<SVM>("SVM45_X_38-2.xml");
    string tname = tempfile("a.json");
    svm2->save(tname + "?base64");
    svm3 = Algorithm::load<SVM>(tname);

    ASSERT_EQ(svm1->getVarCount(), svm2->getVarCount());
    ASSERT_EQ(svm1->getVarCount(), svm3->getVarCount());

    int m = 10000, n = svm1->getVarCount();
    Mat samples(m, n, CV_32F), r1, r2, r3;
    randu(samples, 0., 1.);

    svm1->predict(samples, r1);
    svm2->predict(samples, r2);
    svm3->predict(samples, r3);

    double eps = 1e-4;
    EXPECT_LE(cvtest::norm(r1, r2, NORM_INF), eps);
    EXPECT_LE(cvtest::norm(r1, r3, NORM_INF), eps);

    remove(tname.c_str());
}
Exemplo n.º 18
0
//---------------------------------------------------------------------------
void JrkPlotDialog::createCurve(QString title, QColor cl, bool on, double scale)
{
    QwtPlotCurve *curve;    
    QPen pen;

    curve = new QwtPlotCurve(title);

    pen.setColor(cl);
    pen.setWidth(2);

    curve->setPen(pen);

    curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, true);
    curve->setRenderHint( QwtPlotCurve::RenderAntialiased, true);

#if 0
    QwtSplineCurveFitter* curveFitter = new QwtSplineCurveFitter();
    curveFitter->setSplineSize(500);
    curve->setCurveFitter(curveFitter);
#endif

    curve->attach(ui->jrkPlot);
    showCurve(curve, on);

    jrkdata.push_back(new JrkPlotData(curve, scale, samples()));
    // qDebug("Scale: %f", scale);
}
Exemplo n.º 19
0
void fantasy_sound_device::device_add_mconfig(machine_config &config)
{
	SPEAKER(config, "mono").front_center();

	SNK6502_SOUND(config, m_custom, 0);
	m_custom->add_route(ALL_OUTPUTS, "mono", 0.50);

	samples_device &samples(SAMPLES(config, "samples"));
	samples.set_channels(1);
	samples.set_samples_names(fantasy_sample_names);
	samples.add_route(ALL_OUTPUTS, "mono", 0.5);

	sn76477_device &sn76477_1(SN76477(config, "sn76477.1"));
	// BOMB     GND:    2,9,26,27       +5V: 15,25
	sn76477_1.set_noise_params(RES_K(470), RES_M(1.5), CAP_P(220));
	sn76477_1.set_decay_res(0);
	sn76477_1.set_attack_params(0, 0);
	sn76477_1.set_amp_res(RES_K(470));
	sn76477_1.set_feedback_res(RES_K(4.7));
	sn76477_1.set_vco_params(0, 0, 0);
	sn76477_1.set_pitch_voltage(0);
	sn76477_1.set_slf_params(0, 0);
	sn76477_1.set_oneshot_params(0, 0);
	sn76477_1.set_vco_mode(0);
	sn76477_1.set_mixer_params(0, 1, 0);
	// schematic does not show pin 1 grounded, but it must be.
	// otherwise it is using the VCO for the envelope, but the VCO is not hooked up
	sn76477_1.set_envelope_params(0, 1);
	sn76477_1.set_enable(0);
	sn76477_1.add_route(0, "discrete", 1.0, 0);

	DISCRETE(config, m_discrete, fantasy_discrete);
	m_discrete->add_route(ALL_OUTPUTS, "mono", 0.5);
}
Exemplo n.º 20
0
nsresult
EMEAudioDecoder::GmpInput(MP4Sample* aSample)
{
  MOZ_ASSERT(IsOnGMPThread());
  nsAutoPtr<MP4Sample> sample(aSample);
  if (!mGMP) {
    mCallback->Error();
    return NS_ERROR_FAILURE;
  }

  if (sample->crypto.valid) {
    CDMCaps::AutoLock caps(mProxy->Capabilites());
    MOZ_ASSERT(caps.CanDecryptAndDecodeAudio());
    const auto& keyid = sample->crypto.key;
    if (!caps.IsKeyUsable(keyid)) {
      // DeliverSample assumes responsibility for deleting aSample.
      nsRefPtr<nsIRunnable> task(new DeliverSample(this, sample.forget()));
      caps.CallWhenKeyUsable(keyid, task, mGMPThread);
      return NS_OK;
    }
  }

  gmp::GMPAudioSamplesImpl samples(sample, mAudioChannels, mAudioRate);
  mGMP->Decode(samples);

  mStreamOffset = sample->byte_offset;

  return NS_OK;
}
Exemplo n.º 21
0
 // make a report on the data collected so far and print it to a string buffer
 // The buffer must be allocated by the caller (256 bytes should be enough)
 void report(char *str) const
    {
    int l = sprintf(str, "Statistics on: %s   Num samples = %u SUM=%f\n", _name, samples(), sum());
    if (_samples > 0)
       sprintf(str+l, "MAX=%f MIN=%f Mean=%f StdDev=%f\n",
          maxVal(), minVal(), mean(), stddev());
    }
Exemplo n.º 22
0
void satansat_sound_device::device_add_mconfig(machine_config &config)
{
	SPEAKER(config, "mono").front_center();

	SNK6502_SOUND(config, m_custom, 0);
	m_custom->add_route(ALL_OUTPUTS, "mono", 0.50);

	samples_device &samples(SAMPLES(config, "samples"));
	samples.set_channels(3);
	samples.set_samples_names(vanguard_sample_names);
	samples.add_route(ALL_OUTPUTS, "mono", 0.25);

	sn76477_device &sn76477_1(SN76477(config, "sn76477.1"));
	// ???      GND: 2,26,27        +5V: 15,25
	sn76477_1.set_noise_params(RES_K(470), RES_M(1.5), CAP_P(220));
	sn76477_1.set_decay_res(0);
	sn76477_1.set_attack_params(0, 0);
	sn76477_1.set_amp_res(RES_K(47));
	sn76477_1.set_feedback_res(RES_K(47));
	sn76477_1.set_vco_params(0, 0, 0);
	sn76477_1.set_pitch_voltage(0);
	sn76477_1.set_slf_params(0, 0);
	sn76477_1.set_oneshot_params(0, 0);
	sn76477_1.set_vco_mode(0);
	sn76477_1.set_mixer_params(0, 1, 0);
	sn76477_1.set_envelope_params(1, 1);
	sn76477_1.set_enable(1);
	sn76477_1.add_route(ALL_OUTPUTS, "mono", 1.0);
}
Exemplo n.º 23
0
void DemoQPItem::drawGraphBars(float x, float y, float w, float h, int items, float t) {
    QVarLengthArray<float, 1024> samples(items);
    QVarLengthArray<float, 1024> sx(items); QVarLengthArray<float, 1024> sy(items);
    float dx = w/(items-1);
    float barWidth = dx * 0.8;
    float margin = dx - barWidth;
    int i;

    // Generate positions
    for (i = 0; i<items; i++) {
        samples[i] = 0.5 + sinf(i*0.1+t)*0.5;
    }
    for (i = 0; i < items; i++) {
        sx[i] = x+i*dx + margin/2;
        sy[i] = h*samples[i];
    }

    // Draw graph bars
    m_painter->setBrush(m_color3);
    qreal lineWidth = 0.5 + w * 0.002;
    QPen pen(m_colorBlack, lineWidth);
    pen.setJoinStyle(Qt::MiterJoin);
    m_painter->setPen(pen);
    // TODO: Consider drawRects() instead if it's faster?
    for (i = 0; i < items; i++) {
        m_painter->drawRect((int)sx[i]+0.5, (int)y+2.5, (int)barWidth, (int)sy[i]);
    }
}
Exemplo n.º 24
0
 // make a report on the data collected so far and print it to a stream
 void report(FILE *file) const
    {
    fprintf(file, "Statistics on: %s   Num samples = %u SUM=%f\n", _name, samples(), sum());
    if (_samples > 0)
       fprintf(file, "MAX=%f MIN=%f Mean=%f StdDev=%f\n",
          maxVal(), minVal(), mean(), stddev());
    }
Exemplo n.º 25
0
    void signal::lowpass(double cutoff) {
        // Spectrum parameters
        uint16_t size    = samples();
        uint16_t n       = (size - 1)/2;
        uint16_t nyquist = rate/2;
        double   width   = (double)nyquist/n;

        // Compute spectrum
        // TODO: windowed application over entire signal
        spectrum spec(*this, size);

        for(int i = 0; i < channels; i++) {
            // Kill bins above cutoff
            uint16_t start = (int)ceil(cutoff/width);
            for(int j = start; j <= n; j++) {
                spec[i][j]        = 0;
                spec[i][size - j] = 0;
            }

            // Kill Nyquist bin as necessary
            if((size - 1) % 2) spec[i][n + 1] = 0;
        }

        *this = spec;
    }
Exemplo n.º 26
0
int main (int argc, const char *argv[])
{
    CmdArgParser parser(argc, argv);
    parser.setHeader("Archive Benchmark\n");
    parser.setArgumentsInfo("<index>");
    CmdArgFlag old(parser, "old", "Use old directory file");
    CmdArgInt samples(parser, "samples", "<count>",
                      "Number of samples to write");
    CmdArgString channel_name(parser, "channel", "<name>",
                      "Channel Name");
    CmdArgFlag do_read(parser, "read",
                       "Perform read test");
    
    // defaults
    samples.set(100000);
    channel_name.set("fred");

    if (parser.parse() == false)
        return -1;
    if (parser.getArguments().size() != 1)
    {
        parser.usage();
        return -1;
    }
    stdString index_name = parser.getArgument(0);
    size_t count;
    epicsTime start, stop;
    try
    {
        if (do_read)
        {
            start = epicsTime::getCurrent ();
            if (old)
                count = old_read_samples(index_name, channel_name.get());
            else
                count = read_samples(index_name, channel_name.get());
            stop = epicsTime::getCurrent ();
        }
        else
        {
            count = samples.get();
            start = epicsTime::getCurrent ();
            if (old)
                old_write_samples(index_name, channel_name.get(), count);
            else
                write_samples(index_name, channel_name.get(), count);
            stop = epicsTime::getCurrent ();
        }
        double secs = stop - start;
        printf("%zd values in %g seconds: %g vals/sec\n",
               count, secs,
               (double)count / secs);
    }
    catch (GenericException &e)
    {
        fprintf(stderr, "Error:\n%s\n", e.what());
    }
    return 0;
}
Exemplo n.º 27
0
::DDS::ReturnCode_t read (::DDS::DataReader_ptr reader,
                          ACE_Array<bool>& pub_finished)
{
  R_ptr pt_dr
    = R::_narrow(reader);

  Rimpl* dr_servant =
      ::TAO::DCPS::reference_to_servant< Rimpl, R_ptr>
              (pt_dr);

  const ::CORBA::Long max_read_samples = 100;
  Tseq samples(max_read_samples);
  ::DDS::SampleInfoSeq infos(max_read_samples);

  int samples_recvd = 0;
  DDS::ReturnCode_t status;
  // initialize to zero.

  status = dr_servant->read (
    samples,
    infos,
    max_read_samples,
    ::DDS::NOT_READ_SAMPLE_STATE,
    ::DDS::ANY_VIEW_STATE,
    ::DDS::ANY_INSTANCE_STATE);

  if (status == ::DDS::RETCODE_OK)
    {
      if ((samples[samples.length () - 1].sequence_num == -1)
          || (samples[0].sequence_num == -1))
        {
          for (unsigned i = 0; i < samples.length (); i ++)
            {
              if (samples[i].sequence_num != -1)
                {
                  samples_recvd ++;
                }
              else
                {
                  pub_finished[samples[i].data_source] = true;
                }
            }
        }
      else
        {
          samples_recvd = samples.length ();
        }
    }
  else if (status == ::DDS::RETCODE_NO_DATA)
    {
      ACE_ERROR((LM_ERROR, " Empty read!\n"));
    }
  else
    {
      ACE_OS::printf (" read  data: Error: %d\n", status) ;
    }

  return samples_recvd;
}
Exemplo n.º 28
0
void Histogram::setValue(const double x, const double y)
{
  QVector<QwtIntervalSample> samples(1);
  QwtInterval interval(x - 0.4, x + 0.4);
  interval.setBorderFlags(QwtInterval::ExcludeMaximum);
  samples[0] = QwtIntervalSample(y, interval);
  setData(new QwtIntervalSeriesData(samples));
}
Exemplo n.º 29
0
void AudioBuffer::apply_s16(std::function<float(float)> _fn)
{
	int16_t *data = &at<int16_t>(0);
	for(unsigned i=0; i<samples(); ++i) {
		float result = _fn(s16_to_f32(data[i]));
		data[i] = f32_to_u8(result);
	}
}
Exemplo n.º 30
0
	void Audio::setLoop(const bool loop)
	{
		Siv3DEngine::GetAudio()->setLoop(
			m_handle->id(),
			loop,
			0,
			loop ? samples() - 1 : 0);
	}