%%%  GOP_delegate_estimator.m - a MATLAB script
%%%  Copyright 2012,2016 by Samuel S.-H. Wang
%%%  Noncommercial-use-only license: 
%%%  You may use or modify this software, but only for noncommercial purposes. 
%%%  To seek a commercial-use license, contact the author at sswang@princeton.edu.

% Likelihood analysis of all possible outcomes of election based 
% on the meta-analytical methods of Prof. Sam Wang, Princeton University.

% This routine expects the global variable biaspct

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%% Initialize variables %%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

polls.state=[
 'AZ,UT,WI,NY,CT,DE,MD,PA,RI,IN,NE,WV,OR,WA,CA,MT,NJ,NM,SD '];
polls.EV=[58 40 18 14 13 16 14 17 13 30 36 25 28 14 13 27 51 24 29];
% CD-level WTA rules in HI WI CT MD IN WV CA (see below)
% Other CD-level rules in NY PA RI WA
%    RI: assume Trump gets constant 3 delegates
%    WA: assume Trump gets constant 10 delegates

num_states=size(polls.EV,2);

%assignedEV(3)=sum(polls.EV);
assignedEV(1)=0; assignedEV(2)=0; % do not assume any states are safe - calculate all 2^N possibilities!
% 1=Dem, 2=GOP, 3=uncertain

if ~exist('biaspct','var')
    biaspct=0;
end
forhistory=biaspct==0;

if ~exist('analysisdate','var')
    analysisdate=0;
end

if ~exist('metacalc','var')
    metacalc=1;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% Load and parse polling data %%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% polling data
%            'AZ, UT, WI,NY,CT,DE,MD,PA,RI,IN,NE,WV,OR,WA,CA,  MT,NJ,NM,SD '];
polls.margin=[-99 -99 -99 4 -5 14 19 18 14 14 14 14 14 14 7.5 14 14 -1 14]; % April 2
% NY: only 93-95% of vote is committed, assign +2% per candidate (ok?)
% margins are Trump over #2 candidate, except NY/CT which is margin over 50%

polls.SEM=[5 5 5 5 -1 -1 5 5 -1 -1 -1 -1 -1 -1 5 -1 -1 5 -1];
national_SD_2012=12; % for Romney. Note Trump SD is 10% through WI
polls.SEM(find(polls.SEM==-1))=national_SD_2012;
polls.SEM(find(polls.SEM==5))=10; % force high uncertainty everywhere

fixeddels=758 % April 8th from Taniel spreadsheet https://docs.google.com/spreadsheets/d/167RlmxSvrotSiVHmaQuIio3BbGlCmrUgObX2kHM80yQ/edit?pref=2&pli=1#gid=0
nattrump=40; % from http://elections.huffingtonpost.com/pollster/2016-national-gop-primary#!mindate=2014-06-01&smoothing=less&estimate=custom
% 5 polls 3/29-4/3

%
% Convert the CD-level WTA delegates into a seats-votes-like relationship
%
% CD WTA states are WI CT MD PA IN WV CA; include loophole state PA
% exclude CT because statewide is a different rule and CDs are not close
% note that Romney SD in 2012 in California was 3.6%, MAD-based SD 4.3%.
% Assume SD of 5% within a state. Use tcdf(margin/5,2) to make a long tail
%
CDWTA=[3 7 8 10 12 15]; % WI MD PA IN WV CA
CD_margins=polls.margin(CDWTA)+biaspct;
CD_delegates=[24 24 54 27 9 159]; 
CD_dels_assigned=round(sum(tcdf(CD_margins./max(5,polls.SEM(CDWTA)),2).*CD_delegates))+3+10; % 3+10=RI+WA CDs
[CD_dels_assigned sum(CD_delegates)]
% the denominator above, 5, comes from intrastate SD
% yet this estimate is sensitive to accuracy of CD_margins
% if we increase it, then we are just lowering CD delegates. would that be ok?
fixeddels=fixeddels+CD_dels_assigned

% Proportional rules: NY and CT (complex) and RI, OR, WA, NM
%
% NY: assign proportional as a fixed number, make the rest WTA
ny_proportional=round(min(polls.EV(4)/2,(polls.margin(4)+50+biaspct)/100*polls.EV(4)))
fixeddels=fixeddels+ny_proportional;
polls.EV(4)=polls.EV(4)-ny_proportional;
% hardcode Trump delegates using the NY CD rule: 
% probability Trump below 50% is 1-tcdf(polls.margin(4)/polls.SEM(4),1)
% and if Trump is below <50% with two opponents, >20% standard will certainly be met
ny_CDwise=81-round(27*(1-tcdf((polls.margin(4)+biaspct)/9,2))) % Romney SD was 9% in 2012
fixeddels=fixeddels+ny_CDwise
%
% CT: assign statewide the same way as NY
ct_proportional=round(min(polls.EV(5)/2,(polls.margin(5)+50+biaspct)/100*polls.EV(5)))
fixeddels=fixeddels+ct_proportional
polls.EV(5)=polls.EV(5)-ct_proportional;
fixeddels=fixeddels+15 % assign all 5 CDs to Trump

% Proportional-ish statewide rules: RI, OR, WA, NM
% Treat proportional rules as a fixed number of delegates
% 
propstates=[9 13 14 18];
polls.margin(propstates)=-50; % kill WTA rule
propdels=polls.EV(propstates);
trump=zeros(1,length(propstates))+nattrump+biaspct/2;
proportional_delegates_bound=round(sum(trump.*propdels/100))
fixeddels=fixeddels+proportional_delegates_bound % forget about thresholds since Cruz/Kasich are usually above

assignedEV(3)=sum(polls.EV);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%% Where the magic happens! %%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delegate_median

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%% Plot the histogram %%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close
%figure('Color', 'w')
phandle=plot([1237-fixeddels 1237-fixeddels],[0 max(histogram)*110],'-r','LineWidth',1.5);
leftrange=0;
EVticks=leftrange+50:50:450;
grid on
hold on
bar(histogram*100)
axis([min(EVticks) max(EVticks) 0 max(histogram)*110])
xlabel('New delegates for Trump','FontSize',14);
ylabel('Probability of exact # of delegates (%)','FontSize',14)
set(gcf, 'InvertHardCopy', 'off');
% title('Distribution of possible delegates 3/15 to last primary','FontSize',14)
text(min(EVticks)+3,max(histogram)*104,'under 1237','FontSize',14)
text(max(EVticks)-180,max(histogram)*104,'Trump over 1237 total','FontSize',14)
if analysisdate==0
    datelabel=datestr(now);
else
    datelabel=datestr(analysisdate);
end
text(max(EVticks)-150,max(histogram)*13,datelabel(1:6),'FontSize',12)
text(max(EVticks)-150,max(histogram)*7,'election.princeton.edu','FontSize',12)
% text(leftrange*1.01,max(histogram)*13,datelabel(1:6),'FontSize',12)
% text(leftrange*1.01,max(histogram)*7,'election.princeton.edu','FontSize',12)
%if biaspct==0
%    set(gcf,'PaperPositionMode','auto')
%    print -djpeg EV_histogram_today.jpg
%end

sum(histogram(1237-fixeddels:length(histogram)))

medianEV
fixeddels
modeEV(1)=find(histogram==max(histogram));
medianEV(2)=2474-464-medianEV(1); % noTrump delegates
modeEV(2)=2474-464-modeEV(1); % noTrump delegates
