int main( int argc, const char* argv[] ) { double f = 2.0; double w = 2*PI*f; const uint_t n = 200; double *x = new double[n]; for (uint_t i=0; i<n; i++) { x[i] = sin(i*w/n); printf("s=%f, t=%fs \n", x[i], ((double)i)/n); } printf("\n"); mtpsd<double> spectrum(x, n, 1.5); try { spectrum.compute(); } catch (ERR e) { printf("ERROR: %s\n", e.getmsg()); } for (uint_t i=0; i<n; i++) { printf("S=%f, f=%fHz \n", spectrum(i), spectrum.freq(i)); } }
int cepstrum(double *x,double *y,int ndat) { int i; spectrum(x,y,ndat); for (i=0;i<ndat;i++) y[i] = log(y[i]); spectrum(x,y,ndat); return(0); }
Vector Whitted::raytrace(Vector origin, Vector direction, unsigned int i) const { if(i >= _max_depth) return Vector(0.0f, 0.0f, 0.0f); Vector spectrum(0.0f, 0.0f, 0.0f) ; Hit hit; float d; if(_scene->intersect(origin, direction, hit, d)) { return Vector(1,0,0) ; // TODO all the lights Vector position; Vector light = _scene->one_light()->sample(position) ; Vector to_light = (position-hit.p) / norm(position-hit.p) ; Hit light_hit ; float d ; if(!_scene->intersect(hit.p, to_light, light_hit, d)) spectrum += fmax(dot(to_light, hit.n), 0.0f) * light ; // TODO the specular term } return spectrum ; }
void SpectrumAnalyserThread::calculateSpectrum(const QByteArray &buffer, int inputFrequency, int bytesPerSample, bool isSample,char phoneme) { #ifndef DISABLE_FFT //Q_ASSERT(buffer.size() == m_numSamples * bytesPerSample); // Initialize data array const char *ptr = buffer.constData(); for (int i=0; i<m_numSamples; ++i) { const qint16 pcmSample = *reinterpret_cast<const qint16*>(ptr); // Scale down to range [-1.0, 1.0] const DataType realSample = pcmToReal(pcmSample); const DataType windowedSample = realSample * m_window[i]; m_input[i] = windowedSample; ptr += bytesPerSample; } // Calculate the FFT m_fft->calculateFFT(m_output.data(), m_input.data()); // Analyze output to obtain amplitude and phase for each frequency FrequencySpectrum spectrum(SpectrumLengthSamples); if (isSample) { spectrum.setPhoneme(phoneme); } for (int i=2; i<=m_numSamples/2; ++i) { // Calculate frequency of this complex sample spectrum[i].frequency = qreal(i * inputFrequency) / (m_numSamples); const qreal real = m_output[i]; qreal imag = 0.0; if (i>0 && i<m_numSamples/2) imag = m_output[m_numSamples/2 + i]; const qreal magnitude = sqrt(real*real + imag*imag); qreal amplitude = SpectrumAnalyserMultiplier * log(magnitude); // Bound amplitude to [0.0, 1.0] spectrum[i].clipped = (amplitude > 1.0); amplitude = qMax(qreal(0.0), amplitude); amplitude = qMin(qreal(1.0), amplitude); spectrum[i].amplitude = amplitude; } #endif if (!isSample) { emit calculationComplete(spectrum); } else { emit sampleLoaded(spectrum); } }
static int test6(gs_state * pgs, gs_memory_t * mem) { gs_color_space *pcs; gs_cie_abc *pabc; gs_cie_render *pcrd; static const gs_vector3 white_point = {1, 1, 1}; static const gs_cie_render_proc3 encode_abc = { {render_abc, render_abc, render_abc} }; int code; gs_color_space *rgb_cs; rgb_cs = gs_cspace_new_DeviceRGB(mem); gs_scale(pgs, 150.0, 150.0); gs_translate(pgs, 0.5, 0.5); gs_setcolorspace(pgs, rgb_cs); spectrum(pgs, 5); gs_translate(pgs, 1.2, 0.0); /* We must set the CRD before the color space. */ code = gs_cie_render1_build(&pcrd, mem, "test6"); if (code < 0) return code; gs_cie_render1_initialize(mem, pcrd, NULL, &white_point, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &encode_abc, NULL, NULL); gs_setcolorrendering(pgs, pcrd); gs_cspace_build_CIEABC(&pcs, NULL, mem); /* There should be an API for initializing CIE color spaces too.... */ pabc = pcs->params.abc; pabc->common.points.WhitePoint = white_point; gs_cie_abc_complete(pabc); /* End of initializing the color space. */ gs_setcolorspace(pgs, pcs); spectrum(pgs, 5); gs_free_object(mem, rgb_cs, "test6 rgb_cs"); return 0; }
void BandFilterSpectrogram_drawSpectrumAtNearestTimeSlice (BandFilterSpectrogram me, Graphics g, double time, double fmin, double fmax, double dBmin, double dBmax, int garnish) { if (time < my xmin || time > my xmax) { return; } if (fmin == 0 && fmax == 0) { // autoscaling fmin = my ymin; fmax = my ymax; } if (fmax <= fmin) { fmin = my ymin; fmax = my ymax; } long icol = Matrix_xToNearestColumn (me, time); icol = icol < 1 ? 1 : (icol > my nx ? my nx : icol); autoNUMvector<double> spectrum (1, my ny); for (long i = 1; i <= my ny; i++) { spectrum[i] = my v_getValueAtSample (icol, i, 1); // dB's } long iymin, iymax; if (Matrix_getWindowSamplesY (me, fmin, fmax, &iymin, &iymax) < 2) { // too few values return; } if (dBmin == dBmax) { // autoscaling dBmin = spectrum[iymin]; dBmax = dBmin; for (long i = iymin + 1; i <= iymax; i++) { if (spectrum[i] < dBmin) { dBmin = spectrum[i]; } else if (spectrum[i] > dBmax) { dBmax = spectrum[i]; } } if (dBmin == dBmax) { dBmin -= 1; dBmax += 1; } } Graphics_setWindow (g, fmin, fmax, dBmin, dBmax); Graphics_setInner (g); double x1 = my y1 + (iymin -1) * my dy, y1 = spectrum[iymin]; for (long i = iymin + 1; i <= iymax - 1; i++) { double x2 = my y1 + (i -1) * my dy, y2 = spectrum[i]; double xo1, yo1, xo2, yo2; if (NUMclipLineWithinRectangle (x1, y1, x2, y2, fmin, dBmin, fmax, dBmax, &xo1, &yo1, &xo2, &yo2)) { Graphics_line (g, xo1, yo1, xo2, yo2); } x1 = x2; y1 = y2; } Graphics_unsetInner (g); if (garnish) { Graphics_drawInnerBox (g); Graphics_marksBottom (g, 2, 1, 1, 0); Graphics_marksLeft (g, 2, 1, 1, 0); Graphics_textLeft (g, 1, U"Power (dB)"); Graphics_textBottom (g, 1, Melder_cat (U"Frequency (", my v_getFrequencyUnit (), U")")); } }
/** * Applies the transformation to the signal. * * @param x input signal * @return calculated spectrum */ SpectrumType Dft::fft(const SampleType x[]) { SpectrumType spectrum(N); ComplexType WN = std::exp((-j) * 2.0 * M_PI / static_cast<double>(N)); for (unsigned int k = 0; k < N; ++k) { ComplexType sum(0, 0); for (unsigned int n = 0; n < N; ++n) { sum += x[n] * std::pow(WN, n * k); } spectrum[k] = sum; } return spectrum; }
int main (int argc, char * const argv[]) { // Slurp a truckload of data. size_t bytes; size_t num_samples = 22; unsigned char * buffer = slurp_getopt( argc, argv, SLURP_OPTS, NULL, XMIT_IR|1, &num_samples, &bytes); float * samples = xmalloc(num_samples * sizeof * samples); load_samples(samples, buffer, bytes, num_samples); free(buffer); spectrum(optind < argc ? argv[optind] : NULL, samples, num_samples, false); free(samples); return 0; }
int main(int argc, char *argv[]) { int i, j; int ntrans = 0; int npts = 0; double fwhm = .5; double trans[TAB_SIZE][CRD_SIZE] = {{0.}}; double xmin = 0.; double xmax = 5000.; double xstp = 1.; double pts[5000][CRD_SIZE] = {{0.}}; char inpfile[LGN_SIZE] = ""; char outfile[LGN_SIZE] = ""; rcmdl(argc, argv, inpfile, outfile, &fwhm); rgauss(inpfile, &ntrans, trans, fwhm); if (ntrans == 0) { rtrans(inpfile, &ntrans, trans, fwhm); } printf(" %s: %d transitions\n", argv[1], ntrans); for (i=0; i<ntrans; i++) { printf("%12.6lf%12.6lf%12.6lf\n", trans[i][0], trans[i][1], trans[i][2]); } spectrum(&npts, pts, xmin, xmax, xstp, ntrans, trans); for (i=0; i<npts; i++) { printf("%12.6lf%12.6lf\n", pts[i][0], pts[i][1]); } wspec(outfile, npts, pts); return 0; }
int colleration(double *x,double *y,int ndat) { /* auto colleration */ int i; double *im; double tmp; spectrum(x,y,ndat); im = (double*)calloc(ndat,sizeof(double)); ifft(x,y,im,ndat); tmp=y[0]; for (i=0;i<ndat;i++) y[i] = y[i]/tmp; return(0); }
int main(int argc, char *argv[]) { ScopedMPIComm< MeraculousCounterOptions > world(argc, argv); MemoryUtils::getMemoryUsage(); std::string outputFilename = Options::getOptions().getOutputFile(); try { OptionsBaseInterface::FileListType &inputs = Options::getOptions().getInputFiles(); LOG_VERBOSE_OPTIONAL(1, world.rank() == 0, "Reading Input Files"); ReadSetStream reads(inputs, world.rank(), world.size()); LOG_DEBUG_GATHER(1, MemoryUtils::getMemoryUsage()); KS spectrum(world, KS::estimateRawKmers(world, inputs)); spectrum.buildKmerSpectrum(reads, false); if (Log::isVerbose(1)) { std::string hist = spectrum.getHistogram(false); LOG_VERBOSE_OPTIONAL(1, world.rank() == 0, "Collective Kmer Histogram\n" << hist); } std::string outputFilenameBase = outputFilename + ".mercount.m" + boost::lexical_cast<std::string>(KmerSizer::getSequenceLength()); spectrum.dumpCounts(outputFilenameBase, KmerSpectrumOptions::getOptions().getMinDepth()); outputFilenameBase = outputFilename + ".mergraph.m" + boost::lexical_cast<std::string>(KmerSizer::getSequenceLength()) + ".D" + boost::lexical_cast<std::string>(KmerSpectrumOptions::getOptions().getMinDepth()); spectrum.dumpGraphs(outputFilenameBase, KmerSpectrumOptions::getOptions().getMinDepth()); world.barrier(); LOG_VERBOSE_OPTIONAL(1, world.rank() == 0, "Finished"); } catch (std::exception &e) { LOG_ERROR(1, "MeraculousCounter threw an exception! Aborting...\n\t" << e.what()); world.abort(1); } catch (...) { LOG_ERROR(1, "MeraculousCounter threw an error!"); world.abort(1); } return 0; }
void Whitted::integrate() const { Vector origin, direction ; float d ; Hit hit ; cimg_library::CImg<float> buffer(_camera->width(), _camera->height(), 1, 3, 0.0f) ; for(unsigned int i=0; i<_camera->width(); ++i) for(unsigned int j=0; j<_camera->height(); ++j) { Vector spectrum(0.0f, 0.0f, 0.0f) ; _camera->sample(i+0.5f, j+0.5f, origin, direction) ; spectrum = raytrace(origin, direction, 0) ; buffer(i, j, 0, 0) = 255.0f * spectrum[0] ; buffer(i, j, 0, 1) = 255.0f * spectrum[1] ; buffer(i, j, 0, 2) = 255.0f * spectrum[2] ; } buffer.save(filename().c_str()) ; }
std::vector<float> get_spectrum_1d(const cv::Mat_<float> &im, const int axis, const bool windowing) { if(axis >= im.dims) throw std::invalid_argument("Matrix dimension is too small to compute the spectrum along this axis"); assert(im.isContinuous()); Convolver co(im.size[axis]); if(windowing) co.set_hanning(); std::vector<float> spectrum(co.fourier_size()); std::vector<double> tot(co.fourier_size(), 0.0); std::vector<std::complex<double> > totf(co.fourier_size(), 0.0); unsigned long int step = im.step1(axis); //whatever the real dimension, we fall back to a 3d situation where the axis of interest is y //and either x or z can be of size 1 int nbplanes = 1; for(int d=0; d<axis; ++d) nbplanes *= im.size[d]; int planestep = im.total()/nbplanes; //for each plane for(int i=0; i<nbplanes; ++i) { //for each line for(size_t j=0; j<step; ++j) { co.spectrum(reinterpret_cast<float* const>(im.data) + i*planestep + j, step, &spectrum[0]); for(size_t u=0; u<spectrum.size(); ++u) tot[u] += spectrum[u]; for(size_t u=0; u<spectrum.size(); ++u) totf[u] += co.get_fourier()[u]; } } const double icount = 1.0 / (nbplanes * step); for(size_t i=0; i<tot.size(); ++i) spectrum[i] = tot[i]*icount - std::norm(totf[i]*icount); return spectrum; }
QImage ImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) { QImage result; const QStringList idSegments = id.split(QLatin1Char('/')); if (requestedSize.width() < 1 || requestedSize.height() < 1) { qDebug() << Q_FUNC_INFO << " requestedSize is invalid!" << requestedSize << id; return QImage(); } if (idSegments.count() < 2) { qDebug() << Q_FUNC_INFO << "Not enough parameters for the image provider: " << id; return QImage(); } const QString &elementId = idSegments.at(1); if (idSegments.first() == QStringLiteral("background")) { return renderedSvgElement(elementId, designRenderer(), Qt::KeepAspectRatioByExpanding, size, requestedSize); } else if (idSegments.first() == QStringLiteral("title")) { if (elementId == QStringLiteral("textmask")) result = renderedSvgElement(idSegments.first(), designRenderer(), Qt::KeepAspectRatio, size, requestedSize); else result = spectrum(size, requestedSize); } else if (idSegments.first() == QStringLiteral("specialbutton")) { result = renderedSvgElement(elementId, designRenderer(), Qt::IgnoreAspectRatio, size, requestedSize); } else if (idSegments.first() == buttonString) { result = renderedDesignElement(DesignElementTypeButton, elementId.toInt(), size, requestedSize); } else if (idSegments.first() == frameString) { result = renderedDesignElement(DesignElementTypeFrame, 0, size, requestedSize); } else if (idSegments.first() == QStringLiteral("object")) { result = renderedSvgElement(elementId, objectRenderer(), Qt::KeepAspectRatio, size, requestedSize); } else if (idSegments.first() == QStringLiteral("clock")) { if (idSegments.count() != 4) { qDebug() << Q_FUNC_INFO << "Wrong number of parameters for clock images:" << id; return QImage(); } result = clock(idSegments.at(1).toInt(), idSegments.at(2).toInt(), idSegments.at(3).toInt(), size, requestedSize); } else if (idSegments.first() == QStringLiteral("notes")) { result = notes(elementId.split(QLatin1Char(','), QString::SkipEmptyParts), size, requestedSize); } else if (idSegments.first() == QStringLiteral("quantity")) { if (idSegments.count() != 3) { qDebug() << Q_FUNC_INFO << "Wrong number of parameters for quantity images:" << id; return QImage(); } result = quantity(idSegments.at(1).toInt(), idSegments.at(2), size, requestedSize); } else if (idSegments.first() == QStringLiteral("lessonicon")) { if (idSegments.count() != 3) { qDebug() << Q_FUNC_INFO << "Wrong number of parameters for lessonicon:" << id; return QImage(); } result = renderedLessonIcon(idSegments.at(1), idSegments.at(2).toInt(), size, requestedSize); } else if (idSegments.first() == QStringLiteral("color")) { if (idSegments.count() != 3) { qDebug() << Q_FUNC_INFO << "Wrong number of parameters for color:" << id; return QImage(); } const QColor color(idSegments.at(1)); result = colorBlot(color, idSegments.at(2).toInt(), size, requestedSize); } else { qDebug() << Q_FUNC_INFO << "invalid image Id:" << id; } #if 0 if (idSegments.first() == QStringLiteral("object")) { QPainter p(&result); QPolygon points; for (int i = 0; i < result.width(); i += 2) for (int j = 0; j < result.height(); j += 2) points.append(QPoint(i, j)); p.drawPoints(points); p.setPen(Qt::white); p.translate(1, 1); p.drawPoints(points); } #endif return result; }
// --------------------------------------------------------------------------- // analyze // --------------------------------------------------------------------------- //! Analyze a range of (mono) samples at the given sample rate //! (in Hz) and store the extracted Partials in the Analyzer's //! PartialList (std::list of Partials). Use the specified envelope //! as a frequency reference for Partial tracking. //! //! \param bufBegin is a pointer to a buffer of floating point samples //! \param bufEnd is (one-past) the end of a buffer of floating point //! samples //! \param srate is the sample rate of the samples in the buffer //! \param reference is an Envelope having the approximate //! frequency contour expected of the resulting Partials. // void Analyzer::analyze( const double * bufBegin, const double * bufEnd, double srate, const Envelope & reference ) { // configure the reassigned spectral analyzer, // always use odd-length windows: // Kaiser window double winshape = KaiserWindow::computeShape( sidelobeLevel() ); long winlen = KaiserWindow::computeLength( windowWidth() / srate, winshape ); if (! (winlen % 2)) { ++winlen; } debugger << "Using Kaiser window of length " << winlen << endl; std::vector< double > window( winlen ); KaiserWindow::buildWindow( window, winshape ); std::vector< double > windowDeriv( winlen ); KaiserWindow::buildTimeDerivativeWindow( windowDeriv, winshape ); ReassignedSpectrum spectrum( window, windowDeriv ); // configure the peak selection and partial formation policies: SpectralPeakSelector selector( srate, m_cropTime ); PartialBuilder builder( m_freqDrift, reference ); // configure bw association policy, unless // bandwidth association is disabled: std::unique_ptr< AssociateBandwidth > bwAssociator; if( m_bwAssocParam > 0 ) { debugger << "Using bandwidth association regions of width " << bwRegionWidth() << " Hz" << endl; bwAssociator.reset( new AssociateBandwidth( bwRegionWidth(), srate ) ); } else { debugger << "Bandwidth association disabled" << endl; } // reset envelope builders: m_ampEnvBuilder->reset(); m_f0Builder->reset(); m_partials.clear(); try { const double * winMiddle = bufBegin; // loop over short-time analysis frames: while ( winMiddle < bufEnd ) { // compute the time of this analysis frame: const double currentFrameTime = long(winMiddle - bufBegin) / srate; // compute reassigned spectrum: // sampsBegin is the position of the first sample to be transformed, // sampsEnd is the position after the last sample to be transformed. // (these computations work for odd length windows only) const double * sampsBegin = std::max( winMiddle - (winlen / 2), bufBegin ); const double * sampsEnd = std::min( winMiddle + (winlen / 2) + 1, bufEnd ); spectrum.transform( sampsBegin, winMiddle, sampsEnd ); // extract peaks from the spectrum, and thin Peaks peaks = selector.selectPeaks( spectrum, m_freqFloor ); Peaks::iterator rejected = thinPeaks( peaks, currentFrameTime ); // fix the stored bandwidth values // KLUDGE: need to do this before the bandwidth // associator tries to do its job, because the mixed // derivative is temporarily stored in the Breakpoint // bandwidth!!! FIX!!!! fixBandwidth( peaks ); if ( m_bwAssocParam > 0 ) { bwAssociator->associateBandwidth( peaks.begin(), rejected, peaks.end() ); } // remove rejected Breakpoints (needed above to // compute bandwidth envelopes): peaks.erase( rejected, peaks.end() ); // estimate the amplitude in this frame: m_ampEnvBuilder->build( peaks, currentFrameTime ); // collect amplitudes and frequencies and try to // estimate the fundamental m_f0Builder->build( peaks, currentFrameTime ); // form Partials from the extracted Breakpoints: builder.buildPartials( peaks, currentFrameTime ); // slide the analysis window: winMiddle += long( m_hopTime * srate ); // hop in samples, truncated } // end of loop over short-time frames // unwarp the Partial frequency envelopes: builder.finishBuilding( m_partials ); // fix the frequencies and phases to be consistent. if ( m_phaseCorrect ) { fixFrequency( m_partials.begin(), m_partials.end() ); } // for debugging: /* if ( ! m_ampEnv.empty() ) { LinearEnvelope::iterator peakpos = std::max_element( m_ampEnv.begin(), m_ampEnv.end(), compare2nd<LinearEnvelope::iterator::value_type> ); notifier << "Analyzer found amp peak at time : " << peakpos->first << " value: " << peakpos->second << endl; } */ } catch ( Exception & ex ) { ex.append( "analysis failed." ); throw; } }
/** * Applies the transformation to the signal. * * @param x input signal * @return calculated spectrum */ SpectrumType AquilaFft::fft(const SampleType x[]) { SpectrumType spectrum(N); // bit-reversing the samples - a requirement of radix-2 // instead of reversing in place, put the samples to result array unsigned int a = 1, b = 0, c = 0; std::copy(x, x + N, std::begin(spectrum)); for (b = 1; b < N; ++b) { if (b < a) { spectrum[a - 1] = x[b - 1]; spectrum[b - 1] = x[a - 1]; } c = N / 2; while (c < a) { a -= c; c /= 2; } a += c; } // FFT calculation using "butterflies" // code ported from Matlab, based on book by Tomasz P. Zieliński // FFT stages count unsigned int numStages = static_cast<unsigned int>( std::log(static_cast<double>(N)) / LN_2); // L = 2^k - DFT block length and offset // M = 2^(k-1) - butterflies per block, butterfly width // p - butterfly index // q - block index // r - index of sample in butterfly // Wi - starting value of Fourier base coefficient unsigned int L = 0, M = 0, p = 0, q = 0, r = 0; ComplexType Wi(0, 0), Temp(0, 0); ComplexType** Wi_cache = getCachedFftWi(numStages); // iterate over the stages for (unsigned int k = 1; k <= numStages; ++k) { L = 1 << k; M = 1 << (k - 1); Wi = Wi_cache[k][0]; // iterate over butterflies for (p = 1; p <= M; ++p) { // iterate over blocks for (q = p; q <= N; q += L) { r = q + M; Temp = spectrum[r - 1] * Wi; spectrum[r - 1] = spectrum[q - 1] - Temp; spectrum[q - 1] = spectrum[q - 1] + Temp; } Wi = Wi_cache[k][p]; } } return spectrum; }
extern "C" void flame_get_spectrum(unsigned char *spec, int width, float t1, float t2) { spectrum(t1, t2, width, spec); }
int gmx_relax(int argc,char *argv[]) { const char *desc[] = { "g_noe calculates a NOE spectrum" }; int status; t_topology *top; int i,j,k,natoms,nprot,*prot_ind; int ifit; char *gn_fit; atom_id *ind_fit,*all_at; real *w_rls; rvec *xp; t_pair *pair; matrix box; int step,nre; real t,lambda; real *shifts=NULL; t_filenm fnm[] = { { efTRX, "-f", NULL, ffREAD }, { efTPX, "-s", NULL, ffREAD }, { efNDX, NULL, NULL, ffREAD }, { efDAT, "-d", "shifts", ffREAD }, { efOUT, "-o","spec", ffWRITE }, { efXVG, "-corr", "rij-corr", ffWRITE }, { efXVG, "-noe", "noesy", ffWRITE } }; #define NFILE asize(fnm) static real taum = 0.0, maxdist = 0.6; static int nlevels = 15; static int nrestart = 1; static int maxframes = 100; static bool bFFT = TRUE,bFit = TRUE, bVerbose = TRUE; t_pargs pa[] = { { "-taum", FALSE, etREAL, &taum, "Rotational correlation time for your molecule. It is obligatory to pass this option" }, { "-maxdist", FALSE, etREAL, &maxdist, "Maximum distance to be plotted" }, { "-nlevels", FALSE, etINT, &nlevels, "Number of levels for plotting" }, { "-nframes", FALSE, etINT, &maxframes, "Number of frames in your trajectory. Will stop analysis after this" }, { "-fft", FALSE, etBOOL, &bFFT, "Use FFT for correlation function" }, { "-nrestart", FALSE, etINT, &nrestart, "Number of frames between starting point for computation of ACF without FFT" }, { "-fit", FALSE, etBOOL, &bFit, "Do an optimal superposition on reference structure in tpx file" }, { "-v", FALSE, etBOOL, &bVerbose, "Tell you what I am about to do" } }; CopyRight(stderr,argv[0]); parse_common_args(&argc,argv,PCA_CAN_VIEW | PCA_CAN_TIME | PCA_BE_NICE, NFILE,fnm,asize(pa),pa,asize(desc),desc,0,NULL); if (taum <= 0) gmx_fatal(FARGS,"Please give me a sensible taum!\n"); if (nlevels > 50) { nlevels = 50; fprintf(stderr,"Warning: too many levels, setting to %d\n",nlevels); } top = read_top(ftp2fn(efTPX,NFILE,fnm)); natoms = top->atoms.nr; snew(xp,natoms); read_tpx(ftp2fn(efTPX,NFILE,fnm),&step,&t,&lambda,NULL,box, &natoms,xp,NULL,NULL,NULL); /* Determine the number of protons, and their index numbers * by checking the mass */ nprot = 0; snew(prot_ind,natoms); for(i=0; (i<natoms); i++) if (top->atoms.atom[i].m < 2) { prot_ind[nprot++] = i; } fprintf(stderr,"There %d protons in your topology\n",nprot); snew(pair,(nprot*(nprot-1)/2)); for(i=k=0; (i<nprot); i++) { for(j=i+1; (j<nprot); j++,k++) { pair[k].ai = prot_ind[i]; pair[k].aj = prot_ind[j]; } } sfree(prot_ind); fprintf(stderr,"Select group for root least squares fit\n"); rd_index(ftp2fn(efNDX,NFILE,fnm),1,&ifit,&ind_fit,&gn_fit); if (ifit < 3) gmx_fatal(FARGS,"Need >= 3 points to fit!\n"); /* Make an array with weights for fitting */ snew(w_rls,natoms); for(i=0; (i<ifit); i++) w_rls[ind_fit[i]]=top->atoms.atom[ind_fit[i]].m; /* Prepare reference frame */ snew(all_at,natoms); for(j=0; (j<natoms); j++) all_at[j]=j; rm_pbc(&(top->idef),natoms,box,xp,xp); reset_x(ifit,ind_fit,natoms,all_at,xp,w_rls); sfree(all_at); spectrum(bVerbose, ftp2fn(efTRX,NFILE,fnm),ftp2fn(efDAT,NFILE,fnm), ftp2bSet(efDAT,NFILE,fnm),opt2fn("-corr",NFILE,fnm), opt2fn("-noe",NFILE,fnm), maxframes,bFFT,bFit,nrestart, k,pair,natoms,shifts, taum,maxdist,w_rls,xp,&(top->idef)); thanx(stderr); return 0; }
PowerCepstrogram Sound_to_PowerCepstrogram_hillenbrand (Sound me, double minimumPitch, double dt) { try { // minimum analysis window has 3 periods of lowest pitch double analysisWidth = 3 / minimumPitch; if (analysisWidth > my dx * my nx) { analysisWidth = my dx * my nx; } double t1, samplingFrequency = 1 / my dx; autoSound thee; if (samplingFrequency > 30000) { samplingFrequency = samplingFrequency / 2; thee.reset (Sound_resample (me, samplingFrequency, 1)); } else { thee.reset (Data_copy (me)); } // pre-emphasis with fixed coefficient 0.9 for (long i = thy nx; i > 1; i--) { thy z[1][i] -= 0.9 * thy z[1][i - 1]; } long nosInWindow = analysisWidth * samplingFrequency, nFrames; if (nosInWindow < 8) { Melder_throw ("Analysis window too short."); } Sampled_shortTermAnalysis (thee.peek(), analysisWidth, dt, & nFrames, & t1); autoNUMvector<double> hamming (1, nosInWindow); for (long i = 1; i <= nosInWindow; i++) { hamming[i] = 0.54 -0.46 * cos(2 * NUMpi * (i - 1) / (nosInWindow - 1)); } long nfft = 8; // minimum possible while (nfft < nosInWindow) { nfft *= 2; } long nfftdiv2 = nfft / 2; autoNUMvector<double> fftbuf (1, nfft); // "complex" array autoNUMvector<double> spectrum (1, nfftdiv2 + 1); // +1 needed autoNUMfft_Table fftTable; NUMfft_Table_init (&fftTable, nfft); // sound to spectrum double qmax = 0.5 * nfft / samplingFrequency, dq = qmax / (nfftdiv2 + 1); autoPowerCepstrogram him = PowerCepstrogram_create (my xmin, my xmax, nFrames, dt, t1, 0, qmax, nfftdiv2+1, dq, 0); autoMelderProgress progress (L"Cepstrogram analysis"); for (long iframe = 1; iframe <= nFrames; iframe++) { double tbegin = t1 + (iframe - 1) * dt - analysisWidth / 2; tbegin = tbegin < thy xmin ? thy xmin : tbegin; long istart = Sampled_xToIndex (thee.peek(), tbegin); istart = istart < 1 ? 1 : istart; long iend = istart + nosInWindow - 1; iend = iend > thy nx ? thy nx : iend; for (long i = 1; i <= nosInWindow; i++) { fftbuf[i] = thy z[1][istart + i - 1] * hamming[i]; } for (long i = nosInWindow + 1; i <= nfft; i++) { fftbuf[i] = 0; } NUMfft_forward (&fftTable, fftbuf.peek()); complexfftoutput_to_power (fftbuf.peek(), nfft, spectrum.peek(), true); // log10(|fft|^2) // subtract average double specmean = spectrum[1]; for (long i = 2; i <= nfftdiv2 + 1; i++) { specmean += spectrum[i]; } specmean /= nfftdiv2 + 1; for (long i = 1; i <= nfftdiv2 + 1; i++) { spectrum[i] -= specmean; } /* * Here we diverge from Hillenbrand as he takes the fft of half of the spectral values. * H. forgets that the actual spectrum has nfft/2+1 values. Thefore, we take the inverse * transform because this keeps the number of samples a power of 2. * At the same time this results in twice as much numbers in the quefrency domain, i.e. we end with nfft/2+1 * numbers while H. has only nfft/4! */ fftbuf[1] = spectrum[1]; for (long i = 2; i < nfftdiv2 + 1; i++) { fftbuf[i+i-2] = spectrum[i]; fftbuf[i+i-1] = 0; } fftbuf[nfft] = spectrum[nfftdiv2 + 1]; NUMfft_backward (&fftTable, fftbuf.peek()); for (long i = 1; i <= nfftdiv2 + 1; i++) { his z[i][iframe] = fftbuf[i] * fftbuf[i]; } if ((iframe % 10) == 1) { Melder_progress ((double) iframe / nFrames, L"Cepstrogram analysis of frame ", Melder_integer (iframe), L" out of ", Melder_integer (nFrames), L"."); } } return him.transfer(); } catch (MelderError) { Melder_throw (me, ": no Cepstrogram created."); } }
void analyze(int meascount) { spect_iters = spectrum(); avspect_iters += spect_iters; }
void CTX::process(float* bufi, float* bufq, unsigned int n) { for (unsigned int i = 0U; i < n; i++) { CXBreal(m_iBuf, i) = bufi[i]; CXBimag(m_iBuf, i) = bufq[i]; } CXBhave(m_iBuf) = n; CXBscl(m_iBuf, m_micGain); /* unsigned int n = CXBhave(m_iBuf); for (unsigned int i = 0; i < n; i++) CXBdata(m_iBuf, i) = Cmplx(CXBimag(m_iBuf, i), 0.0F); */ if (m_dcBlockFlag && (m_mode == USB || m_mode == LSB)) m_dcBlock->block(); spectrum(m_iBuf, SPEC_TX_MIC); meter(m_iBuf, TX_MIC); if (m_equaliserFlag && (m_mode == USB || m_mode == LSB || m_mode == AM || m_mode == SAM || m_mode == FMN)) m_equaliser->process(); if (m_speechProcFlag && (m_mode == USB || m_mode == LSB)) m_speechProc->process(); spectrum(m_iBuf, SPEC_TX_POST_COMP); meter(m_iBuf, TX_COMP); m_alc->process(); spectrum(m_iBuf, SPEC_TX_POST_ALC); meter(m_iBuf, TX_ALC); m_modulator->modulate(); if (m_tick == 0UL) m_filter->reset(); // Only active for the third method and zero-IF m_oscillator2->mix(); m_filter->filter(); CXBhave(m_oBuf) = CXBhave(m_iBuf); spectrum(m_oBuf, SPEC_TX_POST_FILT); m_oscillator1->mix(); m_iq->process(); CXBscl(m_oBuf, m_power); meter(m_oBuf, TX_PWR); n = CXBhave(m_oBuf); if (m_swapIQ) { for (unsigned int i = 0U; i < n; i++) { bufq[i] = CXBreal(m_oBuf, i); bufi[i] = CXBimag(m_oBuf, i); } } else { for (unsigned int i = 0U; i < n; i++) { bufi[i] = CXBreal(m_oBuf, i); bufq[i] = CXBimag(m_oBuf, i); } } m_tick++; }
QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels, const int num_samples, const int) { if ( audioFrame.size() > 63 && m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0 // <= 0 if widget is too small (resized by user) ) { if (!m_customFreq) { m_freqMax = freq / 2; } QTime start = QTime::currentTime(); #ifdef DETECT_OVERMODULATION bool overmodulated = false; int overmodulateCount = 0; for (int i = 0; i < audioFrame.size(); i++) { if ( audioFrame[i] == std::numeric_limits<int16_t>::max() || audioFrame[i] == std::numeric_limits<int16_t>::min()) { overmodulateCount++; if (overmodulateCount > 3) { overmodulated = true; break; } } } if (overmodulated) { colorizeFactor = 1; } else { if (colorizeFactor > 0) { colorizeFactor -= .08; if (colorizeFactor < 0) { colorizeFactor = 0; } } } #endif // Determine the window size to use. It should be // * not bigger than the number of samples actually available // * divisible by 2 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt(); if (fftWindow > num_samples) { fftWindow = num_samples; } if ((fftWindow & 1) == 1) { fftWindow--; } // Show the window size used, for information ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString()); // Get the spectral power distribution of the input samples, // using the given window size and function float freqSpectrum[fftWindow/2]; FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt(); m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0); // Store the current FFT window (for the HUD) and run the interpolation // for easy pixel-based dB value access QVector<float> dbMap; m_lastFFTLock.acquire(); m_lastFFT = QVector<float>(fftWindow/2); memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float)); uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1); dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -180); m_lastFFTLock.release(); #ifdef DEBUG_AUDIOSPEC QTime drawTime = QTime::currentTime(); #endif // Draw the spectrum QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32); spectrum.fill(qRgba(0,0,0,0)); const uint w = m_innerScopeRect.width(); const uint h = m_innerScopeRect.height(); const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left(); const uint topDist = m_innerScopeRect.top() - m_scopeRect.top(); QColor spectrumColor(AbstractScopeWidget::colDarkWhite); int yMax; #ifdef DETECT_OVERMODULATION if (colorizeFactor > 0) { QColor col = AbstractScopeWidget::colHighlightDark; QColor spec = spectrumColor; float f = std::sin(M_PI_2 * colorizeFactor); spectrumColor = QColor( (int) (f * col.red() + (1-f) * spec.red()), (int) (f * col.green() + (1-f) * spec.green()), (int) (f * col.blue() + (1-f) * spec.blue()), spec.alpha() ); // Limit the maximum colorization for non-overmodulated frames to better // recognize consecutively overmodulated frames if (colorizeFactor > MAX_OVM_COLOR) { colorizeFactor = MAX_OVM_COLOR; } } #endif #ifdef AUDIOSPEC_LINES QPainter davinci(&spectrum); davinci.setPen(QPen(QBrush(spectrumColor.rgba()), 1, Qt::SolidLine)); #endif for (uint i = 0; i < w; i++) { yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1); if (yMax < 0) { yMax = 0; } else if (yMax >= (int)h) { yMax = h-1; } #ifdef AUDIOSPEC_LINES davinci.drawLine(leftDist + i, topDist + h-1, leftDist + i, topDist + h-1 - yMax); #else for (int y = 0; y < yMax && y < (int)h; y++) { spectrum.setPixel(leftDist + i, topDist + h-y-1, spectrumColor.rgba()); } #endif } // Calculate the peak values. Use the new value if it is bigger, otherwise adapt to lower // values using the Moving Average formula if (m_aShowMax->isChecked()) { davinci.setPen(QPen(QBrush(AbstractScopeWidget::colHighlightLight), 2)); if (m_peaks.size() != fftWindow/2) { m_peaks = QVector<float>(m_lastFFT); } else { for (int i = 0; i < fftWindow/2; i++) { if (m_lastFFT[i] > m_peaks[i]) { m_peaks[i] = m_lastFFT[i]; } else { m_peaks[i] = ALPHA_MOVING_AVG * m_lastFFT[i] + (1-ALPHA_MOVING_AVG) * m_peaks[i]; } } } int prev = 0; m_peakMap = FFTTools::interpolatePeakPreserving(m_peaks, m_innerScopeRect.width(), 0, right, -180); for (uint i = 0; i < w; i++) { yMax = (m_peakMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1); if (yMax < 0) { yMax = 0; } else if (yMax >= (int)h) { yMax = h-1; } davinci.drawLine(leftDist + i-1, topDist + h-prev-1, leftDist + i, topDist + h-yMax-1); spectrum.setPixel(leftDist + i, topDist + h-yMax-1, AbstractScopeWidget::colHighlightLight.rgba()); prev = yMax; } } #ifdef DEBUG_AUDIOSPEC m_showTotal++; m_timeTotal += drawTime.elapsed(); qDebug() << widgetName() << " took " << drawTime.elapsed() << " ms for drawing. Average: " << ((float)m_timeTotal/m_showTotal) ; #endif emit signalScopeRenderingFinished(start.elapsed(), 1); return spectrum; } else { emit signalScopeRenderingFinished(0, 1); return QImage(); } }
int main(int argc, char *argv[]) { srand (42); cxxopts::Options options(argv[0], "Markov Chain Monte Carlo method"); options.add_options("General") ("h,help", "Print help") ("s,spectrum", "Input spectrum", cxxopts::value<std::string>(), "FILE") ("m,matrix", "Fragmentation Marix", cxxopts::value<std::string>(), "FILE") ("r,rule", "Rule graph", cxxopts::value<std::string>(), "FILE") ("precursor", "Precursor mass", cxxopts::value<double>(), "FLOAT") ("min", "Min score", cxxopts::value<double>()->default_value("0"), "FLOAT") ("max", "Max score", cxxopts::value<double>(), "FLOAT") ("charge", "Spectrum parameter", cxxopts::value<unsigned>()->default_value("1"), "FLOAT"); options.add_options("Advanced") ("phi_begin", "Initial phi value (WL option)", cxxopts::value<double>()->default_value("1.822"), "FLOAT") ("phi_end", "Final phi value (WL option)", cxxopts::value<double>()->default_value("1"), "FLOAT") ("step", "Length of Wang-Landau iteration", cxxopts::value<unsigned>()->default_value("10000"), "N") ("run_iter", "Number of Monte-Carlo iterations", cxxopts::value<unsigned>()->default_value("50000"), "N") ("eps", "Accuracy", cxxopts::value<double>()->default_value("0.02"), "FLOAT") ("level", "Quantile level for confident interval", cxxopts::value<double>()->default_value("0.95"), "FLOAT") ("product_ion_thresh", "Score parameter", cxxopts::value<double>()->default_value("0.5"), "FLOAT"); const std::vector<std::string> all_groups({"General", "Advanced"}); // options.parse_positional(std::vector<std::string>({"spectrum", "matrix", "rule"})); options.parse(argc, argv); if (options.count("help")) { std::cout << options.help(all_groups) << std::endl; exit(0); } std::ifstream file_mat(options["matrix"].as<std::string>()); std::ifstream file_rule(options["rule"].as<std::string>()); std::ifstream file_spectrum(options["spectrum"].as<std::string>()); double NLP_MASS = options["precursor"].as<double>(); double MIN_SCORE = options["min"].as<double>(); double MAX_SCORE = options["max"].as<double>(); unsigned CHARGE = options["charge"].as<unsigned>(); double PHI_B = options["phi_begin"].as<double>(); double PHI_E = options["phi_end"].as<double>(); unsigned STEP_LENGTH = options["step"].as<unsigned>(); unsigned MIN_STEPS_RUN = options["run_iter"].as<unsigned>(); double EPS = options["eps"].as<double>(); double LEVEL = options["level"].as<double>(); double PRODUCT_ION_THRESH = options["product_ion_thresh"].as<double>(); std::vector<std::vector<double> > mat; double elem; std::string line; while(!file_mat.eof()) { getline(file_mat, line); std::istringstream iss(line); std::vector<double> row; while (iss >> elem) { row.push_back(elem); } mat.push_back(row); } int nrow = mat.size() - 1; int ncol = mat[0].size(); std::cout << nrow << " " << ncol << std::endl; std::vector<std::pair<unsigned, unsigned> > rule; double elem1, elem2; int i = 0; std::istringstream iss(line); while(file_rule >> elem1 >> elem2) { rule.push_back(std::make_pair(elem1, elem2)); } std::vector<double> exp_spectrum; while(!file_spectrum.eof()) { getline(file_spectrum, line); std::istringstream iss(line); while (iss >> elem) { exp_spectrum.push_back(elem); } } file_mat.close(); file_rule.close(); file_spectrum.close(); pcg_extras::seed_seq_from<std::random_device> rd; // for (int i = 0; i < nrow; ++i) { // for (int j = 0; j < ncol; ++j) { // std::cout << mat[i][j] << " "; // } // std::cout << std::endl; // } // std::cout << " ----------------- " << std::endl; // for (int i = 0; i < rule.size(); ++i) { // std::cout << rule[i].first << " " << rule[i].second << std::endl; // } // std::cout << " ----------------- " << std::endl; // std::cout << MIN_SCORE << " " << MAX_SCORE << " " << PHI_B << " " << // PHI_E << " " << STEP_LENGTH << " " << NLP_MASS << std::endl; // set scorer and metropolis parameters Spectrum spectrum(exp_spectrum, CHARGE); SPCScorer scorer(PRODUCT_ION_THRESH); // std::vector<double> start_mass(st_m, st_m + sizeof(st_m) / sizeof(st_m[0])); // MHstate state(start_mass); MHstate state(ncol, NLP_MASS, rd); Peptide peptide(mat, rule, state.get_current_state_(), NLP_MASS); Metropolis mh(mat, rule, NLP_MASS, MIN_SCORE, MAX_SCORE, state, peptide, spectrum, scorer); // get weights WLsimulator wl(mh, PHI_B, PHI_E, STEP_LENGTH); // wl.print(); // wl.wl_step(rd, PHI_B, true); std::vector<double> weights; weights = wl.wl_full(rd, false); // std::cout << "Wang-Landau weights" << std::endl; // for (auto & w: weights) { // std::cout << w << " " ; // } // std::cout << std::endl << std::endl; // // mh step mh.hit_run(rd, MIN_STEPS_RUN, EPS, LEVEL, weights); return 0; }
spectrum signal::fft(uint16_t points) const { return spectrum(*this, points); }
void C_ColorSelector::draw() { render::get().gradient(area.x, area.y, area.w, area.h, *preview_color, Color::Black, GRADIENT_VERTICAL); render::get().rect(area.x, area.y, area.w, area.h, Color::Black); rect_t n_area = rect_t( area.x, area.y + area.h, 234, 254 ); if (open) { render::get().gradient(n_area.x, n_area.y, n_area.w, n_area.h, Color{ 25, 25, 25 }, Color::Black, GRADIENT_VERTICAL); render::get().rect(n_area.x, n_area.y, n_area.w, n_area.h, Color::Black); n_area = rect_t( n_area.x + 5, n_area.y + 5, n_area.w - 10, n_area.h - 10 ); render::get().gradient(n_area.x, n_area.y, n_area.w, n_area.h, Color{ 35, 35, 35, 255 }, Color::Black, GRADIENT_VERTICAL); render::get().rect(n_area.x, n_area.y, n_area.w, n_area.h, Color::Black); n_area = rect_t( n_area.x + 4, n_area.y + 4, n_area.w - 8, n_area.h - 28 ); spectrum(n_area.x, n_area.y, 216, 216); render::get().rect(n_area.x, n_area.y, n_area.w, n_area.h, Color::Black); rect_t slider_area = rect_t( n_area.x, n_area.y + 218, 216, 11 ); render::get().gradient(slider_area.x, slider_area.y, 108, 11, Color::White, color, GRADIENT_HORIZONTAL); render::get().gradient(slider_area.x + 108, slider_area.y, 108, 11, color, Color::Black, GRADIENT_HORIZONTAL); render::get().rect(slider_area.x, slider_area.y, 216, 11, Color::Black); slider_area.y += 12; float ratio = (brightness - 0.0f) / (2.0f - 0.0f); float location = ratio * 216; int points[6] = { slider_area.x + location, slider_area.y, slider_area.x + location + 4, slider_area.y + 6, slider_area.x + location - 4, slider_area.y + 6, }; render::get().triangle(Vector2D(points[0], points[1]), Vector2D(points[2], points[3]), Vector2D(points[4], points[5]), Color(153, 153, 153)); } }
void analyze(int meascount) { spect_iters = spectrum(); avspect_iters += spect_iters; wavefunc_t(); }