% Cancer Therapy  [page 424, Exe 9.24]
% Researchers in cancer therapy often report only the number of patients
% who survive for a specified period of time after treatment rather than the patients’ actual
% survival times. Suppose that 40% of the patients who undergo the standard treatment are
% known to survive 5 years. A new treatment is administered to 200 patients, and 92 of them
% are still alive after a period of 5 years.
% (a) Formulate the hypotheses for testing the validity of the claim that the new treatment
% is more effective than the standard therapy.
% (b) Test with alpha = 0.01 and state your conclusion; use the rejection-region method.
% (c) Perform the test by finding the p-value.
% (d) What sample size ensures the power of 85% against the alternative H1 : p = 0.5 when
% alpha = 0.01?

%(d1)  
phat = 92/200; p0=0.4; p1 = 0.5; n=200; alpha=0.01;
%power
power =  normcdf( (sqrt(n)*abs(p1 -p0) - ...
    norminv(1-alpha) * sqrt(p0*(1-p0)))/sqrt(p1*(1-p1)) )
%0.7085

kargs = 0:n;
u = 1-binocdf(kargs-1, n, p0)  <= alpha; %indicators 0/1
exactpower  =  sum( binopdf(kargs, n, p1).*u ) 
%0.6896

%twosided alternative
power =  normcdf( (sqrt(n)*abs(p1 -p0) - ...
    norminv(1-alpha/2) * sqrt(p0*(1-p0)))/sqrt(p1*(1-p1)) )
%0. 6197

kargs = 0:n;
u = 2*min(binocdf(kargs, n,p0),1-binocdf(kargs-1, n, p0))  <= alpha; %indicators 0/1
exactpower  =  sum( binopdf(kargs, n, p1).*u ) 
%0.5840
% 


%%
p1=0.5;
beta=0.15 %beta=1-power
e = 0.1 % e = |p0 - p1|
n= (sqrt(p0*(1-p0))* norminv(1-alpha) + ...
    sqrt(p1*(1-p1))*norminv(1-beta))^2/e^2
%274.7223 approx 275

exactpower=0; n=10;
while exactpower < 1-beta
     n=n+1;
     kargs = 0:n;
     u = 1-binocdf(kargs-1, n, p0)  <= alpha; %indicator
     exactpower  =  sum( binopdf(kargs, n, p1).*u ) ;
end     
 disp(['samplesize= ' num2str(n)])
%283

%Sample size two sided
 exactpower=0; n=10;
while exactpower < 1-beta
     n=n+1;
     kargs = 0:n;
     u = 2*min(binocdf(kargs, n,p0),1-binocdf(kargs-1, n, p0))  <= alpha; %indicator
     exactpower  =  sum( binopdf(kargs, n, p1).*u ) ;
end     
 disp(['samplesize= ' num2str(n)])
%324
 
 
 
