% clean the workspace and close all open figures
clear all
close all

  disp('Practicuum: Discrete Distributions in MATLAB')
  lw = 2; 
  set(0, 'DefaultAxesFontSize', 16);
  fs = 15;
  msize = 10;
% end of preabmle--------------------------------------
 
   disp('Discrete')
   %
   disp('Generic Discrete')
   
%   In phase I clinical trials a safe dosage of a drug is assessed.
%   In administering the drug doctors are measuring subject's toxicity 
%   response by grading it from 0 (non-toxic), to 5 (lethal toxicity)  
%   (In CTCAE - Common Terminology Citeria for Adverse Events by National 
%   Institute of Health, Grade refers to the severity of adverse events.
%   Generally, Grade 1 events are mild; Grade 2 are moderate; 
%   Grade 3 are severe; Grade 4 are lifethreatening or disabling; 
%   Grade 5 is death. CTCAE grading is by definition a 5-point scale
%   generally corresponding to mild, moderate, severe, life-threatening
%   and death. This grading system inherently places a value on the 
%   importance of an event, although, there is not necessarily 
%  ``proportionality" among grades (a ``2" is not necessarily twice as bad 
%   as a ``1"). Some adverse events are difficult to ``fit" into this 
%   5 point schema, but altering the general guidelines of severity
%   scaling would render the system useless for comparing results between 
%   trials, an important purpose of the system.)
%   Assume that based on a large number of trials (administration patients
%   with Renal cell carcinoma) the toxicity of drug PNU 
%   (a murine Fab fragment of the monoclonal antibody 5T4 fused to a 
%   mutated superantigen staphylococcal enterotoxin A) at particular 
%   fixed dosage is modeled by discrete random variable
% % 
   X = [- 1 0 1 2 3 4 5 6];
   px = [0 0.620  0.190  0.098  0.067   0.024   0.001 0];
   sum(px)
w=0.05; ms=6; %plotting parameters: width of bar and marker size
xx = X; yyp= px;yyc= cumsum(px);
figure(1)
bar(xx, yyp, w,'b','LineWidth',1)
hold on
plot(xx,yyp, 'ro','MarkerSize',ms, 'MarkerFaceColor','r',...
'MarkerEdgeColor','b')
hold off
axis ([-0.5 5.5 0 0.65])
%print -depsc 'C:\Springer\RanVar\RanVareps\ctcaepdf.eps' 


figure(2)
stairs(xx,yyc,'LineWidth',2)
hold on
plot(xx(2:end)-0.05,yyc(1:end-1),'k>', 'MarkerFaceColor','w')
plot(xx, yyc, 'ko',  'MarkerFaceColor','w', 'MarkerEdgeColor','k' )
axis ([-0.5 5.5 0 1.01])
hold off
%print -depsc 'C:\Springer\RanVar\RanVareps\ctcaecdf.eps' 

   EX=X*px'   %or EX = sum(X .* px)
   %  k-th moment   EXk = (X.^k)*px'
   EX2 = (X.^2) * px' %second moment
   %  Variance (second central moment)
   VarX = EX2 - EX^2 %or VarX=sum( (X-EX).^2 .* px )

%%   
%    subplot(1,2,1)
%    bar(X, px); axis tight
%    colormap white
%    subplot(1,2,2)
%    bar(X, cumsum(px)); axis tight
%    colormap white

%  Expectation
   EX=X*px'   %or EX = sum(X .* px)
   %k-th moment   EXk = (X.^k)*px'
   EX2 = (X.^2) * px'
   VarX = EX2 - EX^2
%%
   disp('Binomial')
   
%  Pot smoking.
%  A nationwide survey of seniors by the University of Michigan reveals
%  that about 70% disapprove of daily pot smoking according to a report in 
%  "Parade," September 14, 1980. If 12 seniors are selected at random 
%  and asked their opinion, find the probability that the number who 
%  disapprove of smoking pot daily is
%    (a) anywhere from 7 to 9;
%    (b) at most 5;
%    (c) not less than 8.
% ================== Solution 
disp('(a) Bin(12, 0.7): P(7 <= X <= 9)');
%(a) using binopdf(x,n,p)
disp('(a)-using pdf'); binopdf(7, 12, 0.70) + ...
                       binopdf(8, 12, 0.70) + binopdf(9, 12, 0.70)
% using binocdf(x, n, p)
disp('(a)-using cdf'); binocdf(9, 12, 0.70) - binocdf(6, 12, 0.70)
%(b) at most five i.e., X <= 5
disp('(b) Bin(12, 0.7): P(X <= 5)'); binocdf(5, 12, 0.70)
%(c) not less than 8 is 8,9,10,11,12 or complement of <=7
disp('(c)  Bin(12, 0.7): P(X >= 8)'); 1-binocdf(7, 12, 0.70)
%---------------------------------
% bar([0:12], binopdf([0:12],12,0.7)); axis tight
%   colormap white
%  % print -deps 'C:\Brani\Courses\bmestatu\Fall2007\binopdf.eps'
% %  
% figure(2)
% bar([0:12], binocdf([0:12],12,0.7)); axis tight
%   colormap white
% %  print -deps 'C:\Brani\Courses\bmestatu\Fall2007\binocdf.eps'


% 
w=0.1; ms=6; %plotting parameters: width of bar and marker size
xx = 0:10; yyp= binopdf(xx,10,0.26);yyc= cumsum(yyp);
figure(3)
bar(xx, yyp, w,'b')
hold on
plot(xx,yyp, 'ro','MarkerSize',ms, 'MarkerFaceColor','r')
hold off
axis tight
%print -depsc 'C:\Springer\RanVar\RanVareps\binopdf.eps' 

figure(4)
xx = [-1 xx]; yyc = [0 yyc];
stairs(xx,yyc,'k','linewidth',2)
hold on
plot(xx(2:end)-0.1,yyc(1:end-1),'k>','MarkerFaceColor','w' )
plot(xx, yyc, 'ko',  'MarkerFaceColor','w'  )
axis([-0.5 10 0 1.01])
hold off
%print -depsc 'C:\Springer\RanVar\RanVareps\binocdf.eps' 

%%
%
   disp('Binomial and Hypergeometric')
%CASES
%  In a group of 40 people 15 are "CASES" and remaining 25
%   are "CONTROLS."  
%  A sample of 10 subjects is selected ((A)with repeating; 
% (B) without repeating). Find the probability 
%    P(at least 2 subjects are CASES) 
%Solution: A - with repeating (binomial); number of cases X
%is at least 2 is complement of X <= 1.

disp('(A) Bin(10, 15/40): P(X >= 2)');  1 - binocdf(1, 10, 15/40)

% or >> 1 - binopdf(0, 10, 15/40) - binopdf(1, 10, 15/40)
  
%B -- without repeating (hypergeometric) hygecdf(x, m,k,n)
% m size of population, k - number of cases among m, n sample size.
disp('(B) HGe(40,15,10): P(X >=2)'); 1 - hygecdf(1, 40, 15, 10)
% or 1 - hygepdf(0, 40, 15, 10)- hygepdf(1, 40, 15, 10)
%
%If m -> infinity and k/m->p,
% hypergeometric(x,m,k,n) approaches binomial(n,p).
disp('(A)=(B) for large population');
  1 - binocdf(1, 10, 150000/400000)
  1 - hygecdf(1, 400000, 150000, 10)  
 
w=0.05; ms=6; %plotting parameters: width of bar and marker size
xx = 0:10; yyp= hygepdf(xx,40,15,10);yyc= cumsum(yyp);
figure(21)
subplot(211)
bar(xx, yyp, w,'b')
hold on
plot(xx,yyp, 'ro','MarkerSize',ms, 'MarkerFaceColor','r')
hold off
axis tight
subplot(212)
stairs(xx,yyc,'k','linewidth',2)
hold on
plot(xx(2:end)-0.1,yyc(1:end-1),'k>','MarkerFaceColor','w' )
plot(xx, yyc, 'ko',  'MarkerFaceColor','w'  )
axis tight
hold off
%print -depsc 'C:\Springer\RanVar\RanVareps\hygepdfcdf.eps' 
 

  
%%
%----------------  
   disp('Poisson')
   
% ---- 
% After 7 days of aggregation,
% microscopy images of two thousand 
% embrionic bodies (EB) are used to assess their area size.
% The probability that area of randomly selected EB  exceeds
% the critical size S_c is 0.001.
% Find the probability that areas of exactly 3 EB's exceed 
% the critical size. We use Poisson approximation to the Binomial
% since n is large, p is small and product n*p is moderate.
disp('Poisson(2): P(X=3)'); poisspdf(3, 2)
%Find the probability that number of  EB's exceeding
% the critical size is between 3 and 11, inclusive.
disp('Poisson(2): P(3 <= X <= 11)'); poisscdf(11, 2)-poisscdf(2, 2)

% figure(3)
% bar([0:10], poisspdf([0:10],2)); axis tight
%   colormap white
% %  print -deps 'C:\Brani\Courses\bmestatu\Fall2007\poisspdf2.eps'
% %  
% % Binomial(n, p) --> Poisson(lambda), lambda=lim(np),n->infinity
%
 w=0.05; ms=6; %plotting parameters: width of bar and marker size
xx = 0:10; yyp= poisspdf(xx,2); yyc=cumsum(yyp);
figure(3)
subplot(211)
bar(xx, yyp, w,'b')
hold on
plot(xx,yyp, 'ro','MarkerSize',ms, 'MarkerFaceColor','r')
hold off
axis([0 10 0 0.3 ])
subplot(212)
stairs(xx,yyc,'k','linewidth',2)
hold on
plot(xx(2:end)-0.1,yyc(1:end-1),'k>','MarkerFaceColor','w' )
plot(xx, yyc, 'ko',  'MarkerFaceColor','w'  )
axis tight
hold off
%print -depsc 'C:\Springer\RanVar\RanVareps\poisspdfcdf.eps' 
 



disp('P(X=3) for Bin(2000, 0.001), Bin(200000, 0.00001), ');
disp(' Bin(20000000, 0.0000001), and Poi(2) ');
format('long')
binopdf(3, 2000, 0.001)
binopdf(3, 200000, 0.00001)
binopdf(3, 20000000, 0.0000001)
poisspdf(3, 2)
format('short')
%%
   disp('Geometric')
% CASES again
% In a large population the prevalence of "CASES" is p=20%.
% Subjects are sampled (if the populatuion is large, it is 
% irrelevant if the sampling is done with or without repeating)
% untill the first case is found.
% The number of CONTROLS sampled before the first CASE is found
% is random variable distributed as Geometric(p).
% Find the probability that we will find 7 CONTROLS before we 
% find the first CASE.
disp('X ~ Geometric(0.2):P(X=7)'); geopdf(7, 0.2)

% Find the probability that the number of
% CONTROLS before the first CASE will be between
% 5 and 11 inclusive.
disp('X ~ Geometric(0.2):P(5 <= X <= 11)'); geocdf(11, 0.2)-geocdf(4,0.2)
%
% bar([0:20], geopdf([0:20],0.2)); axis tight
%   colormap white
%  % print -deps 'geompdf02.eps'
figure(4)
w=0.05; ms=6; %plotting parameters: width of bar and marker size
xx = 0:20; yyp= geopdf(xx,0.2); yyc=cumsum(yyp);
subplot(211)
bar(xx, yyp, w,'b')
hold on
plot(xx,yyp, 'ro','MarkerSize',ms, 'MarkerFaceColor','r')
hold off
axis tight
subplot(212)
stairs(xx,yyc,'k','linewidth',2)
hold on
plot(xx(2:end)-0.1,yyc(1:end-1),'k>','MarkerFaceColor','w' )
plot(xx, yyc, 'ko',  'MarkerFaceColor','w'  )
axis tight
hold off
%print -depsc 'C:\Springer\RanVar\RanVareps\geopdfcdf.eps' 
 
%%
  
%-------------------------------
%  quantiles
figure(5)
qua =[];
for p = 0.00:0.001:1
    qua = [qua binoinv(p, 12, 0.7)];
end
plot([0.00:0.001:1],qua,'k-')
hold on
plot([0.05 0.05],[0 12],'k--')
plot([0.95 0.95],[0 12],'k--')
%print -deps 'binoquant.eps'
%
%
disp('binoinv([0.05 0.95], 12, 0.7)');
binoinv([0.05 0.95], 12, 0.7)

%Binomial Probability Tables
%  X ~ Bin(n, p)  [x, bpdf=P(X=x), bcdf = P(X <= x)]
% binocdf(x, n, p).
disp('binocdf(0:12, 12, 0.7)');
bcdf =binocdf(0:12, 12, 0.7);
disp('binopdf(0:12, 12, 0.7)');
bpdf = binopdf(0:12, 12, 0.7);
table = [(0:12)'  bpdf' bcdf']

%%
%%Sampling from Binomial and Poisson
%  ---- Simulation ------

simu = binornd(12, 0.7, [1,100000]);
  % simu is 10000 observations from Bin(12,0.7)
disp('simu = binornd(12, 0.7, [1,100000]); 12*0.7 - mean(simu)');


12*0.7 - mean(simu) 
  % should be small since the theoretical mean is n*p
disp('simu = binornd(12, 0.7, [1,100000]); 12 * 0.7 * 0.3 - var(simu)');
 
12 * 0.7 * 0.3 - var(simu)
  %should be small since the theoretical variance is n*p*(1-p)
figure(6)
  histp(simu,  10); 
  hold on
  bar((0:12)+1/4, binopdf(0:12, 12, 0.7)); colormap white;
  axis tight
  
% Simulations from Poisson(2)
poi = poissrnd(2, [1, 1000000]);
disp('poi = poissrnd(2, [1, 100000]); mean(poi)');
mean(poi)
disp('poi = poissrnd(2, [1, 100000]); var(poi)');
var(poi)
% Comparison with theoretical moments
[m v]=poisstat(2)

% Simulations from Geometric(0.2)
geo = geornd(0.2, [1, 1000000]);
disp('geo = geornd(0.2, [1, 100000]); mean(geo)');
mean(geo)
disp('geo = geornd(0.2, [1, 100000]); var(geo)');
var(geo)
% Comparison with theoretical moments
[m v]=geostat(0.2)

  