static int stepanalysis(MYFLOAT ***currents,params *genparams) { MYFLOAT ISS1; MYFLOAT ISS2; static COMPLEX *cur_four0=NULL, *cur_four=NULL, *cur_four1=NULL; static COMPLEX *four_smooth0=NULL,*four_smooth1=NULL; int N1 = 0; int N2 =0,ii=0,totfiles=0; MYFLOAT **cur0=NULL,**cur1=NULL,**cur=NULL; /*Parameters */ N1 =(int) ((genparams->t1)/(genparams->dt)); N2 = (int)((genparams->t2)/(genparams->dt)); /* compute autocorrelation to get ISS1 and ISS2 */ printf("computing autocorrelation: "); if (genparams->totfilereq ==1){ WERRS("\n Two files needed in PLATEAU mode"); // ISS1 = autocorrelation(*(*(currents+0)+1),N1); exit(0); } /* Passing Particle Currents in All Files */ cur0 = *(currents+0); ISS1 = autocorrelation(*(cur0+1),N1); cur1 = *(currents+1); ISS2 = autocorrelation(*(cur1+1),N2); printf("ISS1=%e\tISS2=%e\tdeltaI=%e\n",ISS1,ISS2,ISS2-ISS1); }
void autocorrelation_function(double* series, unsigned int size, unsigned int num_lags, double mean, double* acf){ unsigned int i; for(i=0;i<num_lags;i++) acf[i] = autocorrelation(series, size, i+1, mean); }
double partial_autocorrelation(double* series, unsigned int size, unsigned int lag, double mean){ int i, j; double* ac = (double*)malloc(lag*sizeof(double)); double* A = (double*)malloc(lag*lag*sizeof(double)); double* b = (double*)malloc(lag*sizeof(double)); int* ipiv = (int*)malloc(lag*sizeof(int)); for(i=0;i<(int)lag;i++){ ac[i] = autocorrelation(series, size, i+1, mean); b[i] = ac[i]; } for(i=0;i<(int)lag;i++){ for(j=0;j<(int)lag;j++){ if(i==j){ A[lag*i+j] = 1.0f; }else{ A[lag*i+j] = ac[abs(j-i)-1]; } } } LAPACKE_dgesv(LAPACK_ROW_MAJOR, lag, 1, A, lag, ipiv, b, 1); double partial_correlation = b[lag-1]; free(ac); free(A); free(b); free(ipiv); return partial_correlation; }
int main(int argc, const char * argv[]) { // Given code to read in the file MC.txt and store the values in data[i] int i, nbr_of_lines; FILE *in_file; nbr_of_lines = 1e6; /* The number of lines in MC.txt. */ double *data = malloc((nbr_of_lines) * sizeof (double)); /* Read data from file. */ in_file = fopen("MC.txt","r"); for (i=0; i<nbr_of_lines; i++) { fscanf(in_file,"%lf",&data[i]); } fclose(in_file); // Calculation of statistical inefficiency using auto-correlation function double stat_ineff = 0; double auto_correlation = 1; double threshold = pow(M_E, -2); while(auto_correlation >= threshold){ auto_correlation = autocorrelation(stat_ineff, data, nbr_of_lines); stat_ineff++; } printf("statistical inefficiency s = %f\n", stat_ineff); // Calculation of statistical inefficiency using blocked variables FILE *out_file; double *corr_length = malloc((nbr_of_lines / 2.5e3 ) * sizeof(double)); for(i = 0; i < nbr_of_lines / 2.5e3; i++){ corr_length[i] = correlationlength((i + 1), data, nbr_of_lines); } out_file = fopen("corr.dat", "w"); for (i = 0; i < nbr_of_lines / 2.5e3; i++) { fprintf(out_file, "%d\t%f\n", (i + 1), corr_length[i]); } fclose(out_file); free(data); data = NULL; return 0; }
int main(int argc, char *argv[]) { qtimer_t t; assert(qthread_initialize() == QTHREAD_SUCCESS); CHECK_VERBOSE(); t = qtimer_create(); assert(t); qtimer_start(t); qtimer_stop(t); if (qtimer_secs(t) == 0) { fprintf(stderr, "qtimer_secs(t) reported zero length time.\n"); } else if (qtimer_secs(t) < 0) { fprintf(stderr, "qtimer_secs(t) thinks time went backwards (%g).\n", qtimer_secs(t)); } iprintf("time to find self and assert it: %g secs\n", qtimer_secs(t)); qtimer_start(t); qtimer_stop(t); assert(qtimer_secs(t) >= 0.0); if (qtimer_secs(t) == 0.0) { iprintf("inlining reduces calltime to zero (apparently)\n"); } else { iprintf("smallest measurable time: %g secs\n", qtimer_secs(t)); } qtimer_destroy(t); // Now to test fastrand ks_test(); runs(); autocorrelation(); qthread_finalize(); return 0; }
// main analysis function void Helmholtz::analyzeframe() { int n, tindex = timeindex; int mask = framesize - 1; int peak; t_float norm = 1. / sqrt(t_float(framesize * 2)); // copy input to processing buffer for(n=0; n<framesize; n++) processbuf[n] = inputbuf[tindex++ & mask] * norm; // copy for normalization function for(n=0; n<framesize; n++) inputbuf2[n] = inputbuf[tindex++ & mask]; // zeropadding for(n=framesize; n<(framesize<<1); n++) processbuf[n] = 0.; // call analysis procedures autocorrelation(); normalize(); pickpeak(); periodandfidelity(); }
Rhythm::FeatureSet Rhythm::getRemainingFeatures() { FeatureSet output; int frames = intensity.size(); if (frames == 0) return output; // find envelope by convolving each subband with half-hanning window vector<vector<float> > envelope; halfHannConvolve(envelope); // find onset curve by convolving each subband of envelope with canny window vector<float> onset; cannyConvolve(envelope, onset); // normalise onset curve vector<float> onsetNorm; normalise(onset, onsetNorm); // push normalised onset curve Feature f_onset; f_onset.hasTimestamp = true; for (unsigned i = 0; i < onsetNorm.size(); i++) { f_onset.timestamp = Vamp::RealTime::frame2RealTime(i * m_stepSize, m_sampleRate); f_onset.values.clear(); f_onset.values.push_back(onsetNorm.at(i)); output[0].push_back(f_onset); } // find moving average of onset curve and difference vector<float> onsetAverage; vector<float> onsetDiff; movingAverage(onsetNorm, average_window, threshold, onsetAverage, onsetDiff); // push moving average Feature f_avg; f_avg.hasTimestamp = true; for (unsigned i = 0; i < onsetAverage.size(); i++) { f_avg.timestamp = Vamp::RealTime::frame2RealTime(i * m_stepSize, m_sampleRate); f_avg.values.clear(); f_avg.values.push_back(onsetAverage.at(i)); output[1].push_back(f_avg); } // push difference from average Feature f_diff; f_diff.hasTimestamp = true; for (unsigned i = 0; i < onsetDiff.size(); i++) { f_diff.timestamp = Vamp::RealTime::frame2RealTime(i * m_stepSize, m_sampleRate); f_diff.values.clear(); f_diff.values.push_back(onsetDiff.at(i)); output[2].push_back(f_diff); } // choose peaks vector<int> peaks; findOnsetPeaks(onsetDiff, peak_window, peaks); int onsetCount = (int) peaks.size(); // push peaks Feature f_peak; f_peak.hasTimestamp = true; for (unsigned i = 0; i < peaks.size(); i++) { f_peak.timestamp = Vamp::RealTime::frame2RealTime(peaks.at(i) * m_stepSize, m_sampleRate); output[3].push_back(f_peak); } // calculate average onset frequency float averageOnsetFreq = (float) onsetCount / (float) (frames * m_stepSize / m_sampleRate); Feature f_avgOnsetFreq; f_avgOnsetFreq.hasTimestamp = true; f_avgOnsetFreq.timestamp = Vamp::RealTime::fromSeconds(0.0); f_avgOnsetFreq.values.push_back(averageOnsetFreq); output[4].push_back(f_avgOnsetFreq); // calculate rhythm strength float rhythmStrength = findMeanPeak(onset, peaks, 0); Feature f_rhythmStrength; f_rhythmStrength.hasTimestamp = true; f_rhythmStrength.timestamp = Vamp::RealTime::fromSeconds(0.0); f_rhythmStrength.values.push_back(rhythmStrength); output[5].push_back(f_rhythmStrength); // find shift range for autocor float firstShift = (int) round(60.f / max_bpm * m_sampleRate / m_stepSize); float lastShift = (int) round(60.f / min_bpm * m_sampleRate / m_stepSize); // autocorrelation vector<float> autocor; autocorrelation(onsetDiff, firstShift, lastShift, autocor); Feature f_autoCor; f_autoCor.hasTimestamp = true; for (float shift = firstShift; shift < lastShift; shift++) { f_autoCor.timestamp = Vamp::RealTime::frame2RealTime(shift * m_stepSize, m_sampleRate); f_autoCor.values.clear(); f_autoCor.values.push_back(autocor.at(shift - firstShift)); output[6].push_back(f_autoCor); } // find peaks in autocor float percentile = 95; int autocorWindowLength = 3; vector<int> autocorPeaks; vector<int> autocorValleys; findCorrelationPeaks(autocor, percentile, autocorWindowLength, firstShift, autocorPeaks, autocorValleys); // find average corrolation peak float meanCorrelationPeak = findMeanPeak(autocor, autocorPeaks, firstShift); Feature f_meanCorrelationPeak; f_meanCorrelationPeak.hasTimestamp = true; f_meanCorrelationPeak.timestamp = Vamp::RealTime::fromSeconds(0.0); f_meanCorrelationPeak.values.push_back(meanCorrelationPeak); output[7].push_back(f_meanCorrelationPeak); // find peak/valley ratio float meanCorrelationValley = findMeanPeak(autocor, autocorValleys, firstShift) + 0.0001; Feature f_peakValleyRatio; f_peakValleyRatio.hasTimestamp = true; f_peakValleyRatio.timestamp = Vamp::RealTime::fromSeconds(0.0); f_peakValleyRatio.values.push_back( meanCorrelationPeak / meanCorrelationValley); output[8].push_back(f_peakValleyRatio); // find tempo from peaks float tempo = findTempo(autocorPeaks); Feature f_tempo; f_tempo.hasTimestamp = true; f_tempo.timestamp = Vamp::RealTime::fromSeconds(0.0); f_tempo.values.push_back(tempo); output[9].push_back(f_tempo); return output; }
long UnLPC2(LPC_WORD *OutBuf, LPC_WORD *InBuf, short bufsize, short nc, ULONG *Flags) { static LPC_WORD HistBuf[PMAX*2]; static LPC_CORR AcHist[HISTSIZE][PMAX+1]; static int HistNum; LPC_PRAM ref[PMAX]; LPC_CORR ac[PMAX+1]; int i, k; ULONG FlagMask = 1; int zwin = ZWINMIN; if (nc > zwin) zwin = ZWINMAX; if (InBuf == LAW_NULL) // Initialise? { HistNum = 0; for (i = 0; i < nc; i++) ref[i] = 0; for (i = 0; i < PMAX*2; i++) HistBuf[i] = 0; for (i = 0; i < PMAX+1; i++) for (int j = 0; j < HISTSIZE; j++) AcHist[j][i] = 0; // LPCdecode(LAW_NULL, nc, 0, LAW_NULL, LAW_NULL); LPCdecode(NULL, nc, 0, NULL, NULL); return 0; } //if ((bufsize % zwin) != 0) return -3; for (i = 0; i < bufsize; i += zwin) { #if HISTSIZE == 4 for (k = 0; k < nc+1; k++) ac[k] = (XPN)AcHist[0][k] + (XPN)AcHist[1][k] + (XPN)AcHist[2][k] + (XPN)AcHist[3][k]; #else for (k = 0; k < nc+1; k++) { ac[k] = 0; for (int h = 0; h < HISTSIZE; h++) ac[k] = (XPN)ac[k] + (XPN)AcHist[h][k]; } #endif // Decode... if ((*Flags & FlagMask) == 0) { schur(ac, nc, ref); LPCdecode(ref, nc, zwin, InBuf+i, OutBuf+i); } else { LPCinit(); // Re-initialise for (int j = 0; j < zwin; j++) OutBuf[i+j] = InBuf[i+j]; // Copy input to output } FlagMask <<= 1; // Update the AutoCorrelation history data... AddAC(HistBuf, OutBuf+i, nc+1, AcHist[HistNum]); // Process overlap of prev. & current buffer if (++HistNum == HISTSIZE) HistNum = 0; // Increment History counter, wrap-around if needed autocorrelation(zwin, OutBuf+i, nc+1, AcHist[HistNum]); // Update AcHist with current buffer for (k = 0; k < nc; k++) HistBuf[k] = OutBuf[i+k]; // Store beginning of current buffer for next AddAC() } return 0; }
int main (int argc, char * argv[]) { if(argc == 1) { printf("\nNumero di parametri insufficiente!"); printf("\nImpostare tipo di inzializzazione:\n"); printf("\t1 -> a freddo;\n"); printf("\t2 -> a caldo\n\n"); exit(EXIT_FAILURE); } if(argc > 2) { STEPS = atoi(argv[2]); if(STEPS%DBIN != 0) { printf("\n# sweeps non è multiplo intero della lunghezza dei bins!\n\n"); exit(EXIT_FAILURE); } } int Nbins = STEPS/DBIN; int i, step, Dt, bin, t; int choice = 0; double action, Sum, Sum1, Err, Err1; /* Stringhe per il nome del file di output */ char *file_autocorr, *file_action; file_autocorr = malloc(100*sizeof(char)); file_action = malloc(100*sizeof(char)); /* * Vettori utili: * _ state -> contiene la posizione dell'oscillatore in ogni passo del * reticolo (N passi totali); * * _ corrDtstep -> contiene i valori stimati a ciascun passo del Metropolis * di <x_i*x_{i+Dt}>; * * _ Vtemp, Vtemp1 -> vettori ausiliari per costruire i correlatori di x e * di x^2 con il metodo del binning; **/ double *state, *corrDtstep, *Vtemp, *Vtemp1, *autocorr; /* * Clusters jackknife utili: * _ clusterDt -> N cluster jk che contengono i correlatori di x e gli * errori; * * _ clusterSQDt -> cluster jk che contengono i correlatori di x^2 e gli * errori; * * _ DEtemp e EMtemp -> clusters jk ausiliari per il calcolo del gap di * energia e dell'elemento di matrice <0|x|1> **/ cluster *clusterDt, *clusterSQDt; cluster DEtemp, EMtemp; /* Eliminazione dei vecchi dati e creazione cartelle per i nuovi dati * dell'autocorrelazione */ system("rm -r harmosc/autocorrelation"); system("mkdir harmosc/autocorrelation"); /* * File di output utili: * _ out_action -> azione dell'oscillatore armonico in funzione dello sweep * del Metropolis; * * _ out_corr -> correlatori <x_l x_k> ed errori; * * _ out_deltaE -> valori di deltaE (mediato sugli Nbins bin) in funzione di * Dt (variabile della correlazione); * _ out_deltaE_errors -> errori sul calcolo di DeltaE; * * _ out_EM -> valore elemento di matrice di <0|x|1>; * _ out_EM_errors -> errori sul calcolo di <0|x|1>; * * _ out_x2gs -> risultati ed errori di <x^2> sullo stato * fondamentale; * * _ out_corrsq -> correlatori <x^2_l x^2_k> ed errori; * * _ out_autocorr -> files labellati dal valore di Dt in cui viene salvata * la funzione di autocorrelazione per <x_l x_{l+Dt}> */ FILE *out_action, *out_corr, *out_deltaE, *out_EM, *out_deltaE_errors,\ *out_EM_errors, *out_x2gs, *out_corrsq; FILE *out_autocorr[DMAX+1]; out_corr = fopen("harmosc/corr_results.dat","w"); out_deltaE = fopen("harmosc/deltaE_results.dat","a"); out_EM = fopen("harmosc/matrixelement_results.dat","a"); out_deltaE_errors = fopen("harmosc/deltaE_errors.dat","a"); out_EM_errors = fopen("harmosc/matrixelement_errors.dat","a"); out_x2gs = fopen("harmosc/Egs_results.dat", "a"); out_corrsq = fopen("harmosc/corrSQ_results.dat", "a"); for(i=0; i<DMAX+1; i++) { sprintf(file_autocorr, "harmosc/autocorrelation/autocorr_%d", i); out_autocorr[i] = fopen(file_autocorr, "w"); } /* Allocazione vettori e cluster jk utili */ state = malloc(N*sizeof(double)); corrDtstep = malloc((N*STEPS)*sizeof(double)); Vtemp = malloc(N*sizeof(double)); Vtemp1 = malloc(N*sizeof(double)); autocorr = malloc(N*sizeof(double)); clusterDt = malloc(N*sizeof(cluster)); clusterSQDt = malloc(N*sizeof(cluster)); /* Inizializzazione strutture cluster jackknife */ for(Dt=0; Dt<N; Dt++) { cluster_init(clusterDt+Dt,Nbins); cluster_init(clusterSQDt+Dt,Nbins); } cluster_init(&DEtemp,Nbins); cluster_init(&EMtemp,Nbins); srand(time(NULL)); rlxd_init(1,rand()); /* Scelta di inizializzazione "a freddo" o "a caldo" dello stato iniziale */ choice = atoi(argv[1]); switch(choice) { case 1: cold_init(state,N); sprintf(file_action, "harmosc/action_coldinit.dat"); break; case 2: hot_init(state,N); sprintf(file_action, "harmosc/action_hotinit.dat"); break; } out_action = fopen(file_action,"w"); cold_init(Vtemp,N); fprintf(out_action,\ "#\n# Azione euclidea ad ogni sweep dell'algoritmo Metropolis\n"); fprintf(out_action,"# Le colonne sono:\n"); fprintf(out_action,"# Sweep\t azione\n#\n"); /* Valuto l'azione del sistema nella configurazione iniziale * (dipenderà dal tipo di inizializzazione di state scelta) */ action = HOeAction(state,N); fprintf(out_action,"%d\t%e\n", -1, action); /* Finché non si è raggiunto il tempo di termalizzazione NTH faccio evolvere * il sistema con il Metropolis */ for(step=0; step<NTH; step++) { action += HOmetropolis(state,N); fprintf(out_action,"%d\t%e\n", step, action); } bin = 0; /* Raggiunto il tempo di termalizzazione, si fa evolvere il sistema per un * numero STEPS di sweeps del Metropolis utilizzando gli stati ottenuti * per il calcolo della correlazione */ for(step=NTH; step<STEPS+NTH; step++) { action += HOmetropolis(state,N); fprintf(out_action,"%d\t%e\n", step, action); for(Dt=0; Dt<N; Dt++) { Sum = 0; Sum1 = 0; /* media sul vettore di reticolo (somme su i) di x_i*x_{i+K} e di * x^2_i*x^2_{i+K} */ for(i=0; i<N; i++) { Sum += state[i]*state[(i+Dt)%N]; Sum1 += state[i]*state[(i+Dt)%N]*state[i]*state[(i+Dt)%N]; } Vtemp[Dt] += Sum/((double)N); Vtemp1[Dt] += Sum1/((double)N); } /* Salvataggio della media sul bin nell vettore del cluster jackknife */ if((step-NTH+1)%DBIN == 0) { for(Dt=0; Dt<N; Dt++) { clusterDt[Dt].Vec[bin] = Vtemp[Dt]/(double)DBIN; Vtemp[Dt] = 0; clusterSQDt[Dt].Vec[bin] = Vtemp1[Dt]/(double)DBIN; Vtemp1[Dt] = 0; } bin++; } } Sum = 0; Err = 0; /* Calcolo e stampa di media e deviazione standard della media dei * correlatori. */ for(Dt=0; Dt<N; Dt++) { clusterJK(clusterDt+Dt); fprintf(out_corr,"%d\t%e\t%e\n", Dt, clusterDt[Dt].Mean, \ sqrt(clusterDt[Dt].Sigma)); clusterJK(clusterSQDt+Dt); fprintf(out_corrsq, "%d\t%e\t%e\n", Dt, clusterSQDt[Dt].Mean, \ sqrt(clusterSQDt[Dt].Sigma)); /* Calcolo l'elemento di matrice di x^2 sul ground state */ EMtemp = sqrt_jk(clusterSQDt+Dt); Sum += (EMtemp.Mean)/(EMtemp.Sigma); Err += 1.0/(EMtemp.Sigma); } fprintf(out_x2gs, "%e\t%e\n",Sum/Err, sqrt(Err/((double)Nbins))); fprintf(out_x2gs, "%e\n", Sum/Err); /* Calcolo del gap di energia e degli elementi di matrice con varianze. * Si prendono in considerazione soltanto i correlatori per piccoli * valodi di Dt: i valori centrali non hanno un andamento regolare * (si veda dal plot dei correlatori) */ for(Dt=2; Dt<NCL; Dt++) { Sum = 0; Sum1 = 0; Err = 0; Err1 = 0; DEtemp = DeltaE(clusterDt+(Dt-1), clusterDt+Dt, clusterDt+(Dt+1)); EMtemp = MatrixElementX(&DEtemp, clusterDt+Dt, Dt, N); /* Si effettua la media pesata di DeltaE per i valori di Dt * presi in considerazione */ Sum += (DEtemp.Mean)/(DEtemp.Sigma); Sum1 += (EMtemp.Mean)/(EMtemp.Sigma); Err += 1.0/(DEtemp.Sigma); Err1 += 1.0/(EMtemp.Sigma); } fprintf(out_deltaE_errors, "%d\t%e\n", STEPS, sqrt(Err/((double)Nbins))); fprintf(out_EM_errors, "%d\t%e\n", STEPS, sqrt(Err1/((double)Nbins))); fprintf(out_deltaE, "%e\n",Sum/Err); fprintf(out_EM, "%e\n",Sum1/Err1); /* * Calcolo e stampa delle autocorrelazioni per i correlatori delle x per i * primi TMAX+1 valori di Dt */ for(t=0; t<TMAX+1; t++) { autocorrelation(corrDtstep, t, autocorr, N, STEPS); for(Dt=0; Dt<DMAX+1; Dt++) { fprintf(out_autocorr[Dt], "%d\t%e\n", t, autocorr[Dt]); } } for(i=0; i<DMAX+1; i++) fclose(out_autocorr[i]); for(i=0; i<N; i++) { free((clusterDt + i)->Vec); free((clusterSQDt + i)->Vec); } free(clusterDt); free(clusterSQDt); fclose(out_corr); fclose(out_action); fclose(out_deltaE); fclose(out_EM); fclose(out_x2gs); fclose(out_corrsq); fclose(out_deltaE_errors); fclose(out_EM_errors); exit(EXIT_SUCCESS); }