% Code to analyze mark-reencounter data from SFJD area using WinBUgs to 
% estimate pop abundance for Bridge Crk trt sites and Murderers Crk
% control sites. Uses closed-capture model M0.  Compares diff
% in abunance for upper Br. Crk (trtgrp2) to Murderers Crk (trtgrp3).

clear all
close all
clc
cd('C:\Users\MMC\Box Sync\Data\USU\NickFish\Bridge\Abundance');
bugsFolder = 'C:\Users\MMC\WinBUGS14';
workFolder = 'C:\Users\MMC\Box Sync\Data\USU\NickFish\Bridge\Abundance';
outputFolder = 'C:\Users\MMC\Box Sync\Data\USU\NickFish\Bridge\Abundance\Output';

% Simulation inputs
noperiods=18 ;
noperiodsbef=10;  
noperiodsaft=8;
analysisname = 'Abund';
popname = 'UpperBridgeVsMurder'; 

% WinBugs inputs
nochains = 3;
nosamples=5000 ;
noburnin=1000;
nothin=2 ;

% Input data
cd(workFolder);
%make long to get all;
data= xlsread('BridgeAbundRaw.xls', 'BridgeMRdata', 'd2:l300');
vi =  data(:,5)== 2 | data(:,5)==3 ; %only  select upper Br and Murd sites;
data2=data(vi,:);

% Set up matricies for efficient processing
 dentreatbef=zeros(nosamples,noperiodsbef);
 dencontbef=zeros(nosamples,noperiodsbef);
 dentreataft=zeros(nosamples,noperiodsbef);
 dencontaft=zeros(nosamples,noperiodsbef);
 diffbef=zeros(nosamples,noperiodsbef);
 diffaft=zeros(nosamples,noperiodsbef);
 meandiffbef=zeros(nosamples,1);
 meandiffaft=zeros(nosamples,1);
 meandiff=zeros(nosamples,1);
 ratdiff=zeros(nosamples,1);
 
for periodno=1:noperiods
    display 'period = '; disp(periodno);
    
    trtperiod = 2;  %specify whether year is bef or aft treat;
    if periodno <=10 
        trtperiod=1;
    end;
    
        display 'trt prd, 1=bef, 2=aft '; disp(trtperiod);
        
        %read in data
        %subset data by period - streamline later.  vi is virtuous (not really) index
        %and picks cells that satisfy conditions including reaches that have >0 
        %marked - think about if using reaches where r=0 makes sense.  Used
        %in previous analyses so I included.
        %WHAT DO YOU DO WHEN M = 0 - COUNT AS MISSING DATA AND CARRY ON,
        %BUT NOT SURE HOW TO DO THAT.
        %vi = ( data(:,1)==year2 & data(:,7)==fishsize2 & data(:,4)>0 );
        %below I keep reaches with m=0, b/c used in orig data
        vi =  data2(:,3)==periodno ; %only select on period;
        datasamp=data2(vi,:);
        year  = datasamp(:,1);
        reachno = datasamp(:,4);
        trtgrpno = datasamp(:,5);
        reachlen = datasamp(:,9);
        m = datasamp(:,6);
        c = datasamp(:,7);
        r = datasamp(:,8);
        noreaches=length(m); %changes ea period
    
        %no data for some year+sizecls combos - get rid of
        if noreaches > 0
            %for fsake - some c<r and m<r - not possible - Change here 
            for i=1:noreaches;
                if c(i,1)<r(i,1)
                    c(i,1) = r(i,1);
                end;
                if m(i,1)<r(i,1)
                    m(i,1) = r(i,1);
                end;
            end;
                
        nind = (m(:,1)+1)+(c(:,1)+1)-(r(:,1)+1);
                
        % Augmenting the data
        nz = 500;
        Yaug = zeros(nz,2);
 
        % clear out for each output
        N = zeros(noreaches,nosamples);
        p = zeros(noreaches,nosamples);
        D = zeros(noreaches,nosamples+2);
        nhat = zeros(noreaches,1);
        
        for n=1:noreaches; 
             
            % change no m, c, and r into EH
            Y = zeros(nind(n,1),2);
            Y(1:(m(n,1)+1),1)=1;
            Y(1:(r(n,1)+1),2)=1;
            Y((m(n,1)+2):nind(n,1),2)=1;

            % Augmenting the data
            Y = [Y; Yaug];  % concatenate aug EH to data EH
            y = sum(Y,2); %sum across rows;

            % Set up data structure for input to WinBugs (size calcs no columns)
            dataStruct = struct('y', y(:,1), ... 
                'nind', nind(n,1), 'nz', nz, 'J', size(Y,2));

             % Initial values for bugs()
             for i=1:nochains;
                 S.p=rand(1);
                 S.psi=rand(1);
                 initStructs(i) = S;
             end;
           
            % run WinBugs sampler 
            % CHANGE BUGDIR FOR OVER SECURED DESKTOP
            [samples, stats] = matbugs(dataStruct, ...
                    fullfile(pwd, 'Bridge_Bayes_Abund.txt'), ...
                    'init', initStructs, ...
                    'nChains', nochains, ...
                    'view', 0, 'nburnin', noburnin, 'nsamples', nosamples, ...
                    'thin', nothin, ...
                            'monitorParams', {'p', 'N'}, ...
                    'Bugdir', bugsFolder);
            
            %Average across the MCMC samples for each reach      
            N(reachno(n,1),:)=mean(samples.N(:,1:nosamples));
            p(reachno(n,1),:)=mean(samples.p(:,1:nosamples));
            
            D(n,3:nosamples+2)=((N(reachno(n,1),:)/ reachlen(n))*100);
            D(n,1)=trtgrpno(n,1);  %attach treatment group;
            D(n,2)=reachno(n,1);  %attach reachno;
            
            %just for checking against LP estimates
            nhat(reachno(n,1),1) = ( (m(n,1)+1)*(c(n,1)+1)/(r(n,1)+1) ) - 1;
            denhat(reachno(n,1),1) = (nhat(reachno(n,1),1)/reachlen(n) )*100;
            denhat(reachno(n,1),2) = trtgrpno(n,1); 
            denhat(reachno(n,1),3) = reachno(n,1); 
            
         end;    %reaches
        
        %subset out treatment and control reaches;
        vitreat = D(:,1) == 2;
        vicont = D(:,1) == 3;
        Dtreat = D(vitreat,:);
        Dcont = D(vicont,:);
  
        %subset out treatment and control reaches for nhat check;
        vitreatdenhat =  denhat(:,2) == 2 ; 
        vicontdenhat =  denhat(:,2) == 3 ; 
        denhattreat = denhat(vitreatdenhat,:);
        denhatcont = denhat(vicontdenhat,:);
        
        %calc mean across reaches for trta and control groups
        Dtreatmean = mean(log(Dtreat(:,3:nosamples+2)),1); %mean for trt reaches;
        Dcontmean =  mean(log(Dcont(:,3:nosamples+2)),1); %mean for trt reaches;
        denhattreatmean = mean(denhattreat(:,1),1); %mean for trt reaches;
        denhatcontmean = mean(denhatcont(:,1),1); %mean for trt reaches;
        
        %calculate dist of ratios and diffs for trt effect by prd;
  
        if periodno<=noperiodsbef
            dentreatbef(:,periodno)= Dtreatmean';
            dencontbef(:,periodno) = Dcontmean';
            denhattreatbef(periodno,:)= denhattreatmean';
            denhatcontbef(periodno,:) = denhatcontmean';
            diffbef(:,periodno) = dentreatbef(:,periodno)...
                - dencontbef(:,periodno);
        end;
        if periodno>noperiodsbef
            periodnoaft=periodno-noperiodsbef;
            dentreataft(:,periodnoaft)= Dtreatmean';
            dencontaft(:,periodnoaft) = Dcontmean';
            denhattreataft(periodnoaft,:)= denhattreatmean';
            denhatcontaft(periodnoaft,:) = denhatcontmean';
            diffaft(:,periodnoaft) = dentreataft(:,periodnoaft)...
                - dencontaft(:,periodnoaft);
         end;
        %}
      
    end;   %end check to skip if no data for a year+sizeclas
 
            
end;   %noperiods

 %get mean across sites for area summary - histogram
 for i=1:nosamples;
     meandiffbef(i,1)=mean(diffbef(i,1:noperiodsbef));
     meandiffaft(i,1)=mean(diffaft(i,1:noperiodsaft));
     meandiff(i,1)=meandiffaft(i,1)-meandiffbef(i,1);
     ratdiff(i,1)=exp(meandiff(i,1));
 end;


 Bridge_Bayes_Output_Abund; %calls program to output to Excel file;
 cd(workFolder);
