c@243: /*
c@243:  *  cluster_segmenter.c
c@243:  *  soundbite
c@243:  *
c@243:  *  Created by Mark Levy on 06/04/2006.
c@309:  *  Copyright 2006 Centre for Digital Music, Queen Mary, University of London.
c@309: 
c@309:     This program is free software; you can redistribute it and/or
c@309:     modify it under the terms of the GNU General Public License as
c@309:     published by the Free Software Foundation; either version 2 of the
c@309:     License, or (at your option) any later version.  See the file
c@309:     COPYING included with this distribution for more information.
c@243:  *
c@243:  */
c@243: 
c@243: #include "cluster_segmenter.h"
c@243: 
c@243: extern int readmatarray_size(const char *filepath, int n_array, int* t, int* d);
c@243: extern int readmatarray(const char *filepath, int n_array, int t, int d, double** arr);
c@243: 
c@243: /* converts constant-Q features to normalised chroma */
c@243: void cq2chroma(double** cq, int nframes, int ncoeff, int bins, double** chroma)
c@243: {
c@243: 	int noct = ncoeff / bins;	/* number of complete octaves in constant-Q */
c@243: 	int t, b, oct, ix;
c@243: 	//double maxchroma;	/* max chroma value at each time, for normalisation */
c@243: 	//double sum;		/* for normalisation */
c@243: 	
c@243: 	for (t = 0; t < nframes; t++)
c@243: 	{
c@243: 		for (b = 0; b < bins; b++)
c@243: 			chroma[t][b] = 0;
c@243: 		for (oct = 0; oct < noct; oct++)
c@243: 		{
c@243: 			ix = oct * bins;
c@243: 			for (b = 0; b < bins; b++)
c@243: 				chroma[t][b] += fabs(cq[t][ix+b]);
c@243: 		}
c@243: 		/* normalise to unit sum
c@243: 		sum = 0;
c@243: 		for (b = 0; b < bins; b++)
c@243: 			sum += chroma[t][b];
c@243: 		for (b = 0; b < bins; b++)
c@243: 			chroma[t][b] /= sum;
c@245: 		*/
c@243: 		/* normalise to unit max - NO this made results much worse!
c@243: 		maxchroma = 0;
c@243: 		for (b = 0; b < bins; b++)
c@243: 			if (chroma[t][b] > maxchroma)
c@243: 				maxchroma = chroma[t][b];
c@243: 		if (maxchroma > 0)
c@243: 			for (b = 0; b < bins; b++)
c@243: 				chroma[t][b] /= maxchroma;	
c@243: 		*/
c@243: 	}
c@243: }
c@243: 
c@243: /* applies MPEG-7 normalisation to constant-Q features, storing normalised envelope (norm) in last feature dimension */
c@243: void mpeg7_constq(double** features, int nframes, int ncoeff)
c@243: {
c@243: 	int i, j;
c@243: 	double ss;
c@243: 	double env;
c@243: 	double maxenv = 0;
c@243: 	
c@243: 	/* convert const-Q features to dB scale */
c@243: 	for (i = 0; i < nframes; i++)
c@243: 		for (j = 0; j < ncoeff; j++)
c@243: 			features[i][j] = 10.0 * log10(features[i][j]+DBL_EPSILON);
c@243: 	
c@243: 	/* normalise each feature vector and add the norm as an extra feature dimension */	
c@243: 	for (i = 0; i < nframes; i++)
c@243: 	{
c@243: 		ss = 0;
c@243: 		for (j = 0; j < ncoeff; j++)
c@243: 			ss += features[i][j] * features[i][j];
c@243: 		env = sqrt(ss);
c@243: 		for (j = 0; j < ncoeff; j++)
c@243: 			features[i][j] /= env;
c@243: 		features[i][ncoeff] = env;
c@243: 		if (env > maxenv)
c@243: 			maxenv = env;
c@243: 	} 
c@243: 	/* normalise the envelopes */
c@243: 	for (i = 0; i < nframes; i++)
c@243: 		features[i][ncoeff] /= maxenv;	
c@243: }
c@243: 
c@243: /* return histograms h[nx*m] of data x[nx] into m bins using a sliding window of length h_len (MUST BE ODD) */
c@243: /* NB h is a vector in row major order, as required by cluster_melt() */
c@243: /* for historical reasons we normalise the histograms by their norm (not to sum to one) */
c@243: void create_histograms(int* x, int nx, int m, int hlen, double* h)
c@243: {
c@243: 	int i, j, t;
c@243: 	double norm;
c@266: 
c@266: 	for (i = 0; i < nx*m; i++) 
c@266: 	        h[i] = 0;
c@266: 
c@243: 	for (i = hlen/2; i < nx-hlen/2; i++)
c@243: 	{
c@243: 		for (j = 0; j < m; j++)
c@243: 			h[i*m+j] = 0;
c@243: 		for (t = i-hlen/2; t <= i+hlen/2; t++)
c@243: 			++h[i*m+x[t]];
c@243: 		norm = 0;
c@243: 		for (j = 0; j < m; j++)
c@243: 			norm += h[i*m+j] * h[i*m+j];
c@243: 		for (j = 0; j < m; j++)
c@243: 			h[i*m+j] /= norm;
c@243: 	}
c@243: 	
c@243: 	/* duplicate histograms at beginning and end to create one histogram for each data value supplied */
c@243: 	for (i = 0; i < hlen/2; i++)
c@243: 		for (j = 0; j < m; j++)
c@243: 			h[i*m+j] = h[hlen/2*m+j];
c@243: 	for (i = nx-hlen/2; i < nx; i++)
c@243: 		for (j = 0; j < m; j++)
c@243: 			h[i*m+j] = h[(nx-hlen/2-1)*m+j];
c@243: }
c@243: 
c@243: /* segment using HMM and then histogram clustering */
c@243: void cluster_segment(int* q, double** features, int frames_read, int feature_length, int nHMM_states, 
c@243: 					 int histogram_length, int nclusters, int neighbour_limit)
c@243: {
c@243: 	int i, j;
c@243: 	
c@243: 	/*****************************/
c@243: 	if (0) {
c@243: 	/* try just using the predominant bin number as a 'decoded state' */
c@243: 	nHMM_states = feature_length + 1;	/* allow a 'zero' state */
c@243: 	double chroma_thresh = 0.05;
c@243: 	double maxval;
c@243: 	int maxbin;
c@243: 	for (i = 0; i < frames_read; i++)
c@243: 	{
c@243: 		maxval = 0;
c@243: 		for (j = 0; j < feature_length; j++)
c@243: 		{
c@243: 			if (features[i][j] > maxval) 
c@243: 			{
c@243: 				maxval = features[i][j];
c@243: 				maxbin = j;
c@243: 			}				
c@243: 		}
c@243: 		if (maxval > chroma_thresh)
c@243: 			q[i] = maxbin;
c@243: 		else
c@243: 			q[i] = feature_length;
c@243: 	}
c@243: 	
c@243: 	}
c@243: 	if (1) {
c@243: 	/*****************************/
c@243: 		
c@243: 	
c@243: 	/* scale all the features to 'balance covariances' during HMM training */
c@243: 	double scale = 10;
c@243: 	for (i = 0; i < frames_read; i++)
c@243: 		for (j = 0; j < feature_length; j++)
c@243: 			features[i][j] *= scale;
c@243: 	
c@243: 	/* train an HMM on the features */
c@243: 	
c@243: 	/* create a model */
c@243: 	model_t* model = hmm_init(features, frames_read, feature_length, nHMM_states);
c@243: 	
c@243: 	/* train the model */
c@243: 	hmm_train(features, frames_read, model);
c@283: /*	
c@243: 	printf("\n\nafter training:\n");
c@243: 	hmm_print(model);
c@283: */	
c@243: 	/* decode the hidden state sequence */
c@243: 	viterbi_decode(features, frames_read, model, q);  
c@243: 	hmm_close(model);
c@243: 	
c@243: 	/*****************************/
c@243: 	}
c@243: 	/*****************************/
c@243: 	
c@243:     
c@283: /*
c@243: 	fprintf(stderr, "HMM state sequence:\n");
c@243: 	for (i = 0; i < frames_read; i++)
c@243: 		fprintf(stderr, "%d ", q[i]);
c@243: 	fprintf(stderr, "\n\n");
c@283: */
c@243: 	
c@243: 	/* create histograms of states */
c@243: 	double* h = (double*) malloc(frames_read*nHMM_states*sizeof(double));	/* vector in row major order */
c@243: 	create_histograms(q, frames_read, nHMM_states, histogram_length, h);
c@243: 	
c@243: 	/* cluster the histograms */
c@243: 	int nbsched = 20;	/* length of inverse temperature schedule */
c@243: 	double* bsched = (double*) malloc(nbsched*sizeof(double));	/* inverse temperature schedule */
c@243: 	double b0 = 100;
c@243: 	double alpha = 0.7;
c@243: 	bsched[0] = b0;
c@243: 	for (i = 1; i < nbsched; i++)
c@243: 		bsched[i] = alpha * bsched[i-1];
c@243: 	cluster_melt(h, nHMM_states, frames_read, bsched, nbsched, nclusters, neighbour_limit, q);
c@243: 	
c@243: 	/* now q holds a sequence of cluster assignments */
c@243: 	
c@243: 	free(h);  
c@243: 	free(bsched);
c@243: }
c@243: 
c@243: /* segment constant-Q or chroma features */
c@243: void constq_segment(int* q, double** features, int frames_read, int bins, int ncoeff, int feature_type, 
c@243: 			 int nHMM_states, int histogram_length, int nclusters, int neighbour_limit)
c@243: {
c@243: 	int feature_length;
c@243: 	double** chroma;
c@243: 	int i;
c@243: 	
c@243: 	if (feature_type == FEATURE_TYPE_CONSTQ)
c@243: 	{
c@283: /*		fprintf(stderr, "Converting to dB and normalising...\n");
c@283:  */		
c@243: 		mpeg7_constq(features, frames_read, ncoeff);
c@283: /*		
c@243: 		fprintf(stderr, "Running PCA...\n");
c@283: */		
c@243: 		/* do PCA on the features (but not the envelope) */
c@243: 		int ncomponents = 20;
c@243: 		pca_project(features, frames_read, ncoeff, ncomponents);
c@243: 		
c@243: 		/* copy the envelope so that it immediatly follows the chosen components */
c@243: 		for (i = 0; i < frames_read; i++)
c@243: 			features[i][ncomponents] = features[i][ncoeff];	
c@243: 		
c@243: 		feature_length = ncomponents + 1;
c@243: 		
c@243: 		/**************************************
c@243: 		//TEST
c@243: 		// feature file name
c@243: 		char* dir = "/Users/mark/documents/semma/audio/";
c@243: 		char* file_name = (char*) malloc((strlen(dir) + strlen(trackname) + strlen("_features_c20r8h0.2f0.6.mat") + 1)*sizeof(char));
c@243: 		strcpy(file_name, dir);
c@243: 		strcat(file_name, trackname);
c@243: 		strcat(file_name, "_features_c20r8h0.2f0.6.mat");
c@243: 		
c@243: 		// get the features from Matlab from mat-file
c@243: 		int frames_in_file;
c@243: 		readmatarray_size(file_name, 2, &frames_in_file, &feature_length);
c@243: 		readmatarray(file_name, 2, frames_in_file, feature_length, features);
c@243: 		// copy final frame to ensure that we get as many as we expected
c@243: 		int missing_frames = frames_read - frames_in_file;
c@243: 		while (missing_frames > 0)
c@243: 		{
c@243: 			for (i = 0; i < feature_length; i++)
c@243: 				features[frames_read-missing_frames][i] = features[frames_read-missing_frames-1][i];
c@243: 			--missing_frames;
c@243: 		}
c@243: 		
c@243: 		free(file_name);
c@243: 		******************************************/
c@243: 	
c@243: 		cluster_segment(q, features, frames_read, feature_length, nHMM_states, histogram_length, nclusters, neighbour_limit);
c@243: 	}
c@243: 	
c@243: 	if (feature_type == FEATURE_TYPE_CHROMA)
c@243: 	{
c@283: /*
c@243: 		fprintf(stderr, "Converting to chroma features...\n");
c@283: */		
c@243: 		/* convert constant-Q to normalised chroma features */
c@243: 		chroma = (double**) malloc(frames_read*sizeof(double*));
c@243: 		for (i = 0; i < frames_read; i++)
c@243: 			chroma[i] = (double*) malloc(bins*sizeof(double));
c@243: 		cq2chroma(features, frames_read, ncoeff, bins, chroma);
c@243: 		feature_length = bins;
c@243: 		
c@243: 		cluster_segment(q, chroma, frames_read, feature_length, nHMM_states, histogram_length, nclusters, neighbour_limit);
c@243: 	
c@243: 		for (i = 0; i < frames_read; i++)
c@243: 			free(chroma[i]);
c@243: 		free(chroma);
c@243: 	}
c@243: }
c@243: 
c@243: 
c@243: