% Simple statistical TDM demo
% ECE230X
% DRB 11-Apr-2007
%
% This simulation assumes a one bit block size for each source.  Real
% statistical TDM systems would probably use a much bigger block size but the
% point here is to show buffering and congestion.
% -------------------------------------------------------------------------
% USER PARAMETERS BELOW
% -------------------------------------------------------------------------
n = 720;			% number of sources
d = 9600;			% maximum data rate of each source (bps)
b = 0.2;			% percentage of time each source transmits
c = 1.544e6;			% capacity of high speed link (bps)
o = 0.1;			% statistical TDM overhead (percentage)
I = 10;				% number of intervals to simulate
% -------------------------------------------------------------------------

offeredbits = zeros(1,I);
outputnewbits = zeros(1,I+1);
outputbacklog = zeros(1,I+1);
currentbacklog = 0;

C = floor(c*(1-o)/d);		% capacity of high speed link in bits/interval
disp(['Capacity of high speed link (bits/interval): ' num2str(C)]);

clf

for i=1:I,

	s = rand(1,n);
	offeredbits(i) = sum(s<b);	% number of offered bits in interval

	% note that the backlog in interval i is transmitted in interval i+1

	outputbacklog(i+1) = currentbacklog;

	if offeredbits(i)+currentbacklog>C,
		outputnewbits(i+1) = C-outputbacklog(i+1);
		currentbacklog = offeredbits(i)+currentbacklog-C;
	else
		outputnewbits(i+1) = offeredbits(i);
		currentbacklog = 0;
	end

	subplot(2,1,1);
	bar(1:I+1,[offeredbits 0],'facecolor',[0.5 0 0]);
	xlabel('interval');
	ylabel('bits from sources');
	hold on
	plot([0 I+2],[C C],'k--');
	hold off
	axis([0 I+2 0 C*1.5])

	pause

	subplot(2,1,2);
	bar(1:I+1,[outputbacklog; [outputnewbits(1:i) offeredbits(i) zeros(1,I-i)]]','stacked');
	xlabel('interval');
	ylabel('bits from sources');
	hold on
	plot([0 I+2],[C C],'k--');
	hold off
	axis([0 I+2 0 C*1.5])

	pause

	if (currentbacklog>0)&(i<I),
		subplot(2,1,2);
		bar(1:I+1,[[outputbacklog(1:i+1) currentbacklog zeros(1,I-i-1)]; [outputnewbits(1:i+1) zeros(1,I-i)]]','stacked');
		xlabel('interval');
		ylabel('bits from sources');
		hold on
		plot([0 I+2],[C C],'k--');
		hold off
		axis([0 I+2 0 C*1.5])
		pause
	else
		subplot(2,1,2);
		bar(1:I+1,[outputbacklog; outputnewbits]','stacked');
		xlabel('interval');
		ylabel('bits from sources');
		hold on
		plot([0 I+2],[C C],'k--');
		hold off
		axis([0 I+2 0 C*1.5])
	end


end

disp(['Link utilization: ' num2str(mean(outputnewbits(2:I+1)+outputbacklog(2:I+1))/C)]);
