summaryrefslogtreecommitdiff
path: root/libs/qm-dsp/dsp/segmentation/cluster_segmenter.c
blob: 0d2762ee7f1e140e802ccfc87b1392d8bb17a4b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/*
 *  cluster_segmenter.c
 *  soundbite
 *
 *  Created by Mark Levy on 06/04/2006.
 *  Copyright 2006 Centre for Digital Music, Queen Mary, University of London.

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  See the file
    COPYING included with this distribution for more information.
 *
 */

#include "cluster_segmenter.h"

extern int readmatarray_size(const char *filepath, int n_array, int* t, int* d);
extern int readmatarray(const char *filepath, int n_array, int t, int d, double** arr);

/* converts constant-Q features to normalised chroma */
void cq2chroma(double** cq, int nframes, int ncoeff, int bins, double** chroma)
{
	int noct = ncoeff / bins;	/* number of complete octaves in constant-Q */
	int t, b, oct, ix;
	//double maxchroma;	/* max chroma value at each time, for normalisation */
	//double sum;		/* for normalisation */
	
	for (t = 0; t < nframes; t++)
	{
		for (b = 0; b < bins; b++)
			chroma[t][b] = 0;
		for (oct = 0; oct < noct; oct++)
		{
			ix = oct * bins;
			for (b = 0; b < bins; b++)
				chroma[t][b] += fabs(cq[t][ix+b]);
		}
		/* normalise to unit sum
		sum = 0;
		for (b = 0; b < bins; b++)
			sum += chroma[t][b];
		for (b = 0; b < bins; b++)
			chroma[t][b] /= sum;
		*/
		/* normalise to unit max - NO this made results much worse!
		maxchroma = 0;
		for (b = 0; b < bins; b++)
			if (chroma[t][b] > maxchroma)
				maxchroma = chroma[t][b];
		if (maxchroma > 0)
			for (b = 0; b < bins; b++)
				chroma[t][b] /= maxchroma;	
		*/
	}
}

/* applies MPEG-7 normalisation to constant-Q features, storing normalised envelope (norm) in last feature dimension */
void mpeg7_constq(double** features, int nframes, int ncoeff)
{
	int i, j;
	double ss;
	double env;
	double maxenv = 0;
	
	/* convert const-Q features to dB scale */
	for (i = 0; i < nframes; i++)
		for (j = 0; j < ncoeff; j++)
			features[i][j] = 10.0 * log10(features[i][j]+DBL_EPSILON);
	
	/* normalise each feature vector and add the norm as an extra feature dimension */	
	for (i = 0; i < nframes; i++)
	{
		ss = 0;
		for (j = 0; j < ncoeff; j++)
			ss += features[i][j] * features[i][j];
		env = sqrt(ss);
		for (j = 0; j < ncoeff; j++)
			features[i][j] /= env;
		features[i][ncoeff] = env;
		if (env > maxenv)
			maxenv = env;
	}
	/* normalise the envelopes */
	for (i = 0; i < nframes; i++)
		features[i][ncoeff] /= maxenv;	
}

/* return histograms h[nx*m] of data x[nx] into m bins using a sliding window of length h_len (MUST BE ODD) */
/* NB h is a vector in row major order, as required by cluster_melt() */
/* for historical reasons we normalise the histograms by their norm (not to sum to one) */
void create_histograms(int* x, int nx, int m, int hlen, double* h)
{
	int i, j, t;
	double norm;

	for (i = 0; i < nx*m; i++)
	        h[i] = 0;

	for (i = hlen/2; i < nx-hlen/2; i++)
	{
		for (j = 0; j < m; j++)
			h[i*m+j] = 0;
		for (t = i-hlen/2; t <= i+hlen/2; t++)
			++h[i*m+x[t]];
		norm = 0;
		for (j = 0; j < m; j++)
			norm += h[i*m+j] * h[i*m+j];
		for (j = 0; j < m; j++)
			h[i*m+j] /= norm;
	}
	
	/* duplicate histograms at beginning and end to create one histogram for each data value supplied */
	for (i = 0; i < hlen/2; i++)
		for (j = 0; j < m; j++)
			h[i*m+j] = h[hlen/2*m+j];
	for (i = nx-hlen/2; i < nx; i++)
		for (j = 0; j < m; j++)
			h[i*m+j] = h[(nx-hlen/2-1)*m+j];
}

/* segment using HMM and then histogram clustering */
void cluster_segment(int* q, double** features, int frames_read, int feature_length, int nHMM_states,
					 int histogram_length, int nclusters, int neighbour_limit)
{
	int i, j;
	
	/*****************************/
	if (0) {
	/* try just using the predominant bin number as a 'decoded state' */
	nHMM_states = feature_length + 1;	/* allow a 'zero' state */
	double chroma_thresh = 0.05;
	double maxval;
	int maxbin;
	for (i = 0; i < frames_read; i++)
	{
		maxval = 0;
		for (j = 0; j < feature_length; j++)
		{
			if (features[i][j] > maxval)
			{
				maxval = features[i][j];
				maxbin = j;
			}				
		}
		if (maxval > chroma_thresh)
			q[i] = maxbin;
		else
			q[i] = feature_length;
	}
	
	}
	if (1) {
	/*****************************/
		
	
	/* scale all the features to 'balance covariances' during HMM training */
	double scale = 10;
	for (i = 0; i < frames_read; i++)
		for (j = 0; j < feature_length; j++)
			features[i][j] *= scale;
	
	/* train an HMM on the features */
	
	/* create a model */
	model_t* model = hmm_init(features, frames_read, feature_length, nHMM_states);
	
	/* train the model */
	hmm_train(features, frames_read, model);
/*	
	printf("\n\nafter training:\n");
	hmm_print(model);
*/	
	/* decode the hidden state sequence */
	viterbi_decode(features, frames_read, model, q);
	hmm_close(model);
	
	/*****************************/
	}
	/*****************************/
	

/*
	fprintf(stderr, "HMM state sequence:\n");
	for (i = 0; i < frames_read; i++)
		fprintf(stderr, "%d ", q[i]);
	fprintf(stderr, "\n\n");
*/
	
	/* create histograms of states */
	double* h = (double*) malloc(frames_read*nHMM_states*sizeof(double));	/* vector in row major order */
	create_histograms(q, frames_read, nHMM_states, histogram_length, h);
	
	/* cluster the histograms */
	int nbsched = 20;	/* length of inverse temperature schedule */
	double* bsched = (double*) malloc(nbsched*sizeof(double));	/* inverse temperature schedule */
	double b0 = 100;
	double alpha = 0.7;
	bsched[0] = b0;
	for (i = 1; i < nbsched; i++)
		bsched[i] = alpha * bsched[i-1];
	cluster_melt(h, nHMM_states, frames_read, bsched, nbsched, nclusters, neighbour_limit, q);
	
	/* now q holds a sequence of cluster assignments */
	
	free(h);
	free(bsched);
}

/* segment constant-Q or chroma features */
void constq_segment(int* q, double** features, int frames_read, int bins, int ncoeff, int feature_type,
			 int nHMM_states, int histogram_length, int nclusters, int neighbour_limit)
{
	int feature_length;
	double** chroma;
	int i;
	
	if (feature_type == FEATURE_TYPE_CONSTQ)
	{
/*		fprintf(stderr, "Converting to dB and normalising...\n");
 */		
		mpeg7_constq(features, frames_read, ncoeff);
/*		
		fprintf(stderr, "Running PCA...\n");
*/		
		/* do PCA on the features (but not the envelope) */
		int ncomponents = 20;
		pca_project(features, frames_read, ncoeff, ncomponents);
		
		/* copy the envelope so that it immediatly follows the chosen components */
		for (i = 0; i < frames_read; i++)
			features[i][ncomponents] = features[i][ncoeff];	
		
		feature_length = ncomponents + 1;
		
		/**************************************
		//TEST
		// feature file name
		char* dir = "/Users/mark/documents/semma/audio/";
		char* file_name = (char*) malloc((strlen(dir) + strlen(trackname) + strlen("_features_c20r8h0.2f0.6.mat") + 1)*sizeof(char));
		strcpy(file_name, dir);
		strcat(file_name, trackname);
		strcat(file_name, "_features_c20r8h0.2f0.6.mat");
		
		// get the features from Matlab from mat-file
		int frames_in_file;
		readmatarray_size(file_name, 2, &frames_in_file, &feature_length);
		readmatarray(file_name, 2, frames_in_file, feature_length, features);
		// copy final frame to ensure that we get as many as we expected
		int missing_frames = frames_read - frames_in_file;
		while (missing_frames > 0)
		{
			for (i = 0; i < feature_length; i++)
				features[frames_read-missing_frames][i] = features[frames_read-missing_frames-1][i];
			--missing_frames;
		}
		
		free(file_name);
		******************************************/
	
		cluster_segment(q, features, frames_read, feature_length, nHMM_states, histogram_length, nclusters, neighbour_limit);
	}
	
	if (feature_type == FEATURE_TYPE_CHROMA)
	{
/*
		fprintf(stderr, "Converting to chroma features...\n");
*/		
		/* convert constant-Q to normalised chroma features */
		chroma = (double**) malloc(frames_read*sizeof(double*));
		for (i = 0; i < frames_read; i++)
			chroma[i] = (double*) malloc(bins*sizeof(double));
		cq2chroma(features, frames_read, ncoeff, bins, chroma);
		feature_length = bins;
		
		cluster_segment(q, chroma, frames_read, feature_length, nHMM_states, histogram_length, nclusters, neighbour_limit);
	
		for (i = 0; i < frames_read; i++)
			free(chroma[i]);
		free(chroma);
	}
}