% a random choice may leads to 
sample(Sample):-
	sample0(Sample).
sample(Sample):-
	sample(Sample).



sample0((Goal1,Goal2)):-
	!, sample0(Goal1),sample0(Goal2). 	% conjunction
%sample0(Goal):-
%	\+(clause(Goal,_)),!,Goal.	% system predicate: e.g true and asserta
sample0(true):-!.
sample0(last_ele(List,Pre,Last)):-!,last_ele(List,Pre,Last).
sample0(\+Goal):-!,\+Goal.
sample0(Head):-
	bagof([Head,Body,N],clause(Head,Body,N),Bag), % N is the reference to the clause in the database
	random_clause(Head,Body,Bag), % random choice
	!, sample0(Body). 

random_clause(Head,Body,Bag):-
	Rand is random,%random(Rand),%write('check Random'),write(Rand),nl, % 0-1 random number because the cumulative probability is between 0-1
	choose(Bag,Head,Body,0,Rand,Sum).

choose([],_,_,_,_,0).
choose([[Head,Body,N]|Bag],Head1,Body1,SoFar,Rand,Rest):-
	label(N,P), SoFar1 is SoFar+P,
	choose(Bag,Head1,Body1,SoFar1,Rand,Rest1),
	Rest is Rest1+P,
	((var(Body1),P1 is SoFar/(SoFar+Rest),Rand>=P1,Head1=Head,Body1=Body); % if this is the case, then 
	true).



% sample(Head,Times,Samples)
sample(Head,0,[]):-!.
sample(Head0,Times,[Head|Samples]):-
	copy_term(Head0,Head),sample(Head),
	NTimes is Times-1,
	sample(Head0,NTimes,Samples).	

	
/* Test Example
% since it is used as a ratio, so it does not matter whether 
label(N,1):- clause(a(1),true,N).
label(N,2):- clause(a(2),true,N).

:- dynamic a/1.
a(1).
a(2).*/