function varargout = Step2ds(varargin)
% STEP2DS M-file for Step2ds.fig
%      STEP2DS, by itself, creates a new STEP2DS or raises the existing
%      singleton*.
%
%      H = STEP2DS returns the handle to a new STEP2DS or the handle to
%      the existing singleton*.
%
%      STEP2DS('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in STEP2DS.M with the given input arguments.
%
%      STEP2DS('Property','Value',...) creates a new STEP2DS or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Step2ds_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Step2ds_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Step2ds

% Last Modified by GUIDE v2.5 10-Aug-2009 16:21:56

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @Step2ds_OpeningFcn, ...
    'gui_OutputFcn',  @Step2ds_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Step2ds is made visible.
function Step2ds_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Step2ds (see VARARGIN)

%close previous window
close(varargin{4}{1});

%retrieve parameters
global param;
param=varargin{4}{2};

%load logo
logo=imread('logo_BMI.jpg');
image(logo);
axis off;

% Choose default command line output for Step2ds
handles.output = hObject;

%read data from file
fid=fopen(param.dataset);
%create format string
format='';
for i=1:param.varnumber
    format=strcat(format,'%s');
end


param.data=textscan(fid,format,'delimiter','\t','headerLines',param.headerlines);
fclose(fid);


%substitute missing values with the mode
for i=1:param.varnumber
    index_NA=find(strcmpi(param.data{i},param.missing));
    if (not(isempty(index_NA)))
        %string without NA
        temps=param.data{i}(setdiff(1:length(param.data{i}),index_NA));
        %count string occurrences
        %(tabulate(x) creates a frequency table of data in vector x
        %1st column: the unique values of x;
        %2nd column: the number of instances of each value)
        count=tabulate(temps);
        [ma ind]=max(cell2num(count(:,2)));
        %in the case max is more than 1
        ind=ind(1);
        param.data{i}(index_NA)=count(ind,1);
    end
end


%according to the network type chosen at step1 different controls are
%displayed

%common controls: maxpar, Bayes factor
mbf=javax.swing.SpinnerNumberModel(1, 1, +100, 1);
mpar=javax.swing.SpinnerNumberModel(2, 1, param.varnumber-1,1);
bfspin=uicomponent('style','JSpinner','Model',mbf,'position',[375 370 100 25]);
param.bf=bfspin;
parspin=uicomponent('style','JSpinner','Model',mpar,'position',[375 335 100 25]);
param.maxpar=parspin;

param.savedir=0;

%progression bar
global bar;
bar=uicomponent('style','JProgressBar','minimum',0,'position',[220 6 290 28]);
set(bar,'Visible','off');
guidata(hObject,handles);

%by default set order with the order of vars
param.order=1:param.varnumber;

%load list of variables
set(handles.varlist,'String',param.labels);

%find variables states and calculate node size
for i=1:param.varnumber
    temp=param.data{i};
    param.states{i}=unique(temp);
    param.ns(i)=length(param.states{i});
    clear temp
end

%warning: one or more variables have more than 30 states: maybe var type is
%continuous?
if any(param.ns>20)
    msgbox('There is at least one variable with more than 20 possible states! Please check that network type has been correctly selected.','Warning!!','warn');    
end

param.stateshow=param.states;
set(handles.varvalues,'String',param.stateshow{1});

%map variables into numbers according to the position in param.states
%(alphabetical order)
for i=1:param.varnumber
    temp=zeros(length(param.data{i}),1);
    for j=1:param.ns(i)
        for k=1:length(param.data{i})
            if(strcmp(param.data{i}{k},param.states{i}(j)))
                temp(k)=j;
            end
        end
    end
    param.data{i}=temp;
end

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Step2ds wait for user response (see UIRESUME)
% uiwait(handles.figure);


% --- Outputs from this function are returned to the command line.
function varargout = Step2ds_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in back.
function back_Callback(hObject, eventdata, handles)
% hObject    handle to back (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
%go back to previous window
h=openfig('Step1.fig','reuse');
guidata(hObject,handles);
eventData=[];
varargin{1}='Step2ds'; %in varargin there is the name of the calling form
varargin{2}=param;
Step1(h,eventData,handles,varargin);



% --- Executes on selection change in varlist.
function varlist_Callback(hObject, eventdata, handles)
% hObject    handle to varlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
indice=get(hObject,'Value');
set(handles.varvalues,'String',param.stateshow{indice});
if(indice==1)
    set(handles.up,'Enable','inactive');
else
    set(handles.up,'Enable','on');
end
if(indice==param.varnumber)
    set(handles.down,'Enable','inactive');
else
    set(handles.down,'Enable','on');
end

% Hints: contents = get(hObject,'String') returns varlist contents as cell array
%        contents{get(hObject,'Value')} returns selected item from varlist


% --- Executes during object creation, after setting all properties.
function varlist_CreateFcn(hObject, eventdata, handles)
% hObject    handle to varlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in varvalues.
function varvalues_Callback(hObject, eventdata, handles)
% hObject    handle to varvalues (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns varvalues contents as cell array
%        contents{get(hObject,'Value')} returns selected item from varvalues


% --- Executes during object creation, after setting all properties.
function varvalues_CreateFcn(hObject, eventdata, handles)
% hObject    handle to varvalues (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in up.
function up_Callback(hObject, eventdata, handles)
% hObject    handle to up (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
%need to modify string of combo box, order and states
i=get(handles.varlist,'Value');
if(i>1)
    temp=param.order(i-1);
    param.order(i-1)=param.order(i);
    param.order(i)=temp;
    temp=param.stateshow(i-1);
    param.stateshow(i-1)=param.stateshow(i);
    param.stateshow(i)=temp;
    stringa_combo=get(handles.varlist,'String');
    temp=stringa_combo(i-1);
    stringa_combo(i-1)=stringa_combo(i);
    stringa_combo(i)=temp;
    set(handles.varlist,'String',stringa_combo);
    set(handles.varlist,'Value',i-1);
else
    msgbox('The variable is already on the top of list!','Attention','warn');
end


% --- Executes on button press in down.
function down_Callback(hObject, eventdata, handles)
% hObject    handle to down (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
%need to modify string of combo box, order and states
i=get(handles.varlist,'Value');
if(i<param.varnumber)
    temp=param.order(i+1);
    param.order(i+1)=param.order(i);
    param.order(i)=temp;
    temp=param.stateshow(i+1);
    param.stateshow(i+1)=param.stateshow(i);
    param.stateshow(i)=temp;
    stringa_combo=get(handles.varlist,'String');
    temp=stringa_combo(i+1);
    stringa_combo(i+1)=stringa_combo(i);
    stringa_combo(i)=temp;
    set(handles.varlist,'String',stringa_combo);
    set(handles.varlist,'Value',i+1);
else
    msgbox('The variable is already on the bottom of list!','Attention','warn');
end



% --- Executes on button press in browsedir.
function browsedir_Callback(hObject, eventdata, handles)
% hObject    handle to browsedir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global param;
param.savedir=uigetdir;
param.savedir=fullfile(param.savedir,'results');
if(param.savedir~=0)
    set(handles.savedir,'String',param.savedir);
end


% --- Executes on button press in learn.
function learn_Callback(hObject, eventdata, handles)
% hObject    handle to learn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%see what type of network has been chosen
global param;
global bar;

%retrieve parameter values
bf=get(param.bf,'Value');
maxpar=get(param.maxpar,'Value');

%visualize controls for progression bar
set(handles.help,'Visible','off');
set(bar,'Visible','on');
guidata(hObject,handles);
pause(0.1);

%check that a save dir has been chosen
if(param.savedir==0)
    %hide progress bar
    set(bar,'Visible','off');
    set(bar,'value',0);
    guidata(hObject,handles);
    msgbox('You must select a directory to save results before continuing!','Error!','error');
    return;
end

dag = learn_struct_K2_f(cell2mat(param.data)', param.ns, param.order,bf, 'max_fan_in',maxpar);

%%
%estimate parameters
%Make a tabula rasa

bnet = mk_bnet(dag, param.ns, 'names', param.labels);

%Bayesian estimation of parameters
for i=1:param.varnumber
    bnet.CPD{i} = tabular_CPD(bnet, i, 'prior_type', 'dirichlet', 'dirichlet_weight', 1);
end

bnet = bayes_update_params(bnet,  cell2mat(param.data)');

% View the learned parameters 
CPT = cell(1,param.varnumber);

for i=1:param.varnumber
    s=struct(bnet.CPD{i});  % violate object privacy
    CPT{i}=s.CPT;
end

mkdir(param.savedir)
write_probs_discrete(param.labels, param.states, CPT, dag, param.savedir)
%%

if isdeployed
    diruse=ctfroot;
     diruse=fullfile(diruse, 'Bayes');
else
    diruse=cd;
end

BayesGraph(dag,param.labels, diruse);
writeGML(dag,param.labels,param.savedir);

%hide progress bar
set(bar,'Visible','off');
set(bar,'value',0);
set(handles.help,'Visible','on');
guidata(hObject,handles);


% --- Executes on button press in help.
function help_Callback(hObject, eventdata, handles)
% hObject    handle to help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Help_Step2_discrete


% --- Executes on button press in help_BF.
function help_BF_Callback(hObject, eventdata, handles)
% hObject    handle to help_BF (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Help_BF

% --- Executes on button press in help_maxpar.
function help_maxpar_Callback(hObject, eventdata, handles)
% hObject    handle to help_maxpar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Help_maxpar

