% CREATEFEATURES reads the DNA sequencing trace files in the
% SCF directory and their corresponding labels. It then transforms the
% trace into a set of features saved in a suitable format that WEKA can use. 
%
% n: the number of trace files
n=2301;
% m: the number of features
m=8;
% Reading SCF data
fprintf('Reading chromatograms and their labels\n');
% Reading labels. See ../data/README for the format.
labels = load('../data/labels.txt');
labelstxt={'Low-Quality','High-Quality','No-Data','Cant-Decide'};
data=cell(n,1);
for i=1:n
    [a,b]=scfread(sprintf('../data/SCF/%d.scf',i));
    data{i}.data=[a.A      a.C      a.G      a.T     ]';
    data{i}.prob=[b.prob_A b.prob_C b.prob_G b.prob_T]';
    data{i}.label=labels(i,2);
end

% Creating features
features = zeros(n,m);
for i=1:n
    fprintf('Creating features for trace %4d\n',i);
    % 1) signal: mean 
    features(i,1) = mean(data{i}.data(:));
    % 2) signal: std 
    features(i,2) = std(data{i}.data(:));
    % 3) signal: median
    features(i,3) = median(data{i}.data(:));
    % 4) scores: mean 
    features(i,4) = mean(data{i}.prob(:));
    % 5) scores: std 
    features(i,5) = std(data{i}.prob(:));
    % 6) scores: median
    features(i,6) = median(data{i}.prob(:));
    % 7) number of bases
    features(i,7) = size(data{i}.prob,2);
    % 8) scores: average of overall scores
    features(i,8) = mean(sum(data{i}.prob));
end

% Writing the features in ARFF format to be used in WEKA.
arff='../data/features.arff';
fprintf('Writing ARFF to %s\n',arff);
fd=fopen(arff,'w');
fprintf(fd,'@RELATION SEQUAL\n');
fprintf(fd,'\n');
for j=1:m
    fprintf(fd,sprintf('@ATTRIBUTE feature%02d  NUMERIC\n',j));
end
fprintf(fd,'@ATTRIBUTE class     {Low-Quality,High-Quality}\n');
fprintf(fd,'@DATA\n');
for i=1:n
    if data{i}.label < 3
        for j=1:m
            fprintf(fd,'%10.5f,',features(i,j));
        end
        fprintf(fd,'%s\n',labelstxt{data{i}.label});
    end
end
fclose(fd);
