%%%  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 -99 0  13 8  12  10  7 -15 10 10 10  2 -19 10 -12 -25]; % April 17
polls.margin=[-99 -99 -99 -99 0  13 8  12  10  7 -15 10 -10 -25 2 -19 10 -12 -25]; % April 20
polls.margin=[-99 -99 -99 -99 7 53 28 26 47  3 -23 15 -6 -4 24 -31 36 -1 -40]; % April 20 "N"'s Google Correlate estimate
polls.margin=[-99 -99 -99 -99 -1 31 10 10.5 10 7 -15 10 -17 -20 4 -19 22 -20 -20]; % April 21
polls.margin=[-99 -99 -99 -99 0  31 10 17 19.5 1 -15 10 -17 -20 12 -19 22 -20 -20]; % April 25

polls.SEM=   [5    5   5  5  5   5  5   5  5  5 -1  5 -1 -1  5  -1  5  5 -1]; % -1=imputed
% the above states have imputed values of margin done using the
% county-based method. also include Cruz bonus of +6%
%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%
% April 9: national Trump margin +14
% April 13: Trump +9%
% April 17: Trump +17% (n=5)

national_SD_2012=10; % Note Trump SD is 10% through WI
polls.SEM(find(polls.SEM==-1))=national_SD_2012; % high uncertainty for imputed states
% polls.SEM(find(polls.SEM==5))=10; % force high uncertainty everywhere
PA_loyalty = 0.8; % Assume 80% loyalty rate in PA: http://triblive.com/news/allegheny/10229809-74/delegates-candidates-district

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

%
% 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*PA_loyalty 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
%x ny_proportional=round(min(polls.EV(4)/2,(polls.margin(4)+50+biaspct)/100*polls.EV(4)))
% ny_proportional=round(min(polls.EV(4)/2,(polls.margin(4)+50)/100*polls.EV(4))) % Cruz version
% "Cruz version" means that bias comes from undercount of Cruz support
% 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
% ny_CDwise=81-round(27*(1-tcdf((polls.margin(4))/9,2))) % Cruz version; assume high spread (9%)
% 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)))
ct_proportional=round(min(polls.EV(5)/2,(polls.margin(5)+50)/100*polls.EV(5))) % Cruz version
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=[49.5 45 45 24]+biaspct/2; %swing version
trump=[49.5 35 30 24]; %Cruz version
% trump=[66 35 39 43]; %R / Google Correlate

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

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
