Last active
March 13, 2019 21:02
-
-
Save dkohlsdorf/6c388bd2c9006e9a28e3 to your computer and use it in GitHub Desktop.
Audio Tracer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package processing.signals; | |
import java.util.ArrayList; | |
import processing.utils.ProbabilityUtils; | |
/** | |
* Viterbi Style Whistle Tracing | |
* | |
* @author Daniel Kohlsdorf | |
*/ | |
public class MotionWhistleTracer { | |
/** | |
* Probability defined by magnitude of each sin / cosine component. | |
*/ | |
public double[] mag_pdf(double[] dft) { | |
double pdf[] = new double[dft.length]; | |
double sum = 0.0; | |
for (int i = 0; i < pdf.length; i++) { | |
sum += dft[i]; | |
pdf[i] = dft[i]; | |
} | |
for (int i = 0; i < pdf.length; i++) { | |
pdf[i] = ProbabilityUtils.lg(pdf[i] / sum); | |
} | |
return pdf; | |
} | |
public double[] trace(ArrayList<double[]> spec, double variance) { | |
int N = spec.size(); | |
int D = spec.get(0).length; | |
double v[][] = new double[N][D]; | |
double var[][] = new double[N][D]; | |
double velocity[][] = new double[N][D]; | |
int bt_ptr[][] = new int[N][D]; | |
v[0] = mag_pdf(spec.get(0)); | |
for (int i = 0; i < D; i++) { | |
velocity[0][i] = 1; | |
var[0][i] = variance; | |
} | |
for (int t = 1; t < N; t++) { | |
double obs[] = mag_pdf(spec.get(t)); | |
for (int f = 0; f < D; f++) { | |
double max_ll = ProbabilityUtils.ZERO; | |
int max_f = 0; | |
for (int _f = 0; _f < D; _f++) { | |
double ll = ProbabilityUtils.lgnormpdf(new double[]{f}, new double[]{velocity[t - 1][_f] + _f}, new double[]{variance}); | |
ll += + v[t - 1][_f]; | |
if (ll > max_ll && _f != f) { | |
max_ll = ll; | |
max_f = _f; | |
} | |
} | |
velocity[t][f] = (f - max_f); | |
v[t][f] = max_ll + obs[f]; | |
bt_ptr[t][f] = max_f; | |
} | |
} | |
double path[] = new double[N]; | |
double max = ProbabilityUtils.ZERO; | |
int max_ptr = 0; | |
for (int i = 0; i < D; i++) { | |
if (v[N - 1][i] > max) { | |
max = v[N - 1][i]; | |
max_ptr = i; | |
} | |
} | |
path[N - 1] = max_ptr; | |
for (int i = N - 2; i > 0; i--) { | |
path[i] = bt_ptr[i][max_ptr]; | |
max_ptr = bt_ptr[i][max_ptr]; | |
} | |
return path; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment