/* ========================================================================== */ 
/* DRAW AT RANDOM P PERCENTS OF EXAMPLES (int) AND WRITE THEM IN A NEW FILE   */
/* ========================================================================== */


   /* create a file containing positive and negative examples */
draw_examples(
                 File_in,   % file containing intensional examples (int)
                 File_out,  % file that will contain drawn examples (int)
                 P_pos,     % percentage of positive examples to draw,
                 P_neg      % percentage of negative examples to draw
               ) :-                
               
   use_module(library(random)), 

   getenv('LEAR_DIR', Lear),
   
   atom_concat(Lear, '/file.pl', File),
   use_module(File),

   atom_concat(Lear, '/counter.pl', Counter),
   use_module(Counter),  

   atom_concat(Lear, '/list.pl', List),
   use_module(List),

   atom_concat(Lear, '/randomize.pl', Random),
   use_module(Random),

   init_randomize,

   atom_concat(File_in, '.int', File_in1),
   bk:consult(File_in1),

   atom_concat(File_out,'.int', File_out1),
   open(File_out1, write, Stream),
   
   write(Stream, ':- discontiguous pos/2, neg/2, target/2, domains/2.'),
   nl(Stream),
   nl(Stream),
   
   reset_count(nb_examples),
   
   get_positive_examples(LPos, LPos_target, LPos_domain),  
   draw_the_examples(pos, P_pos, LPos, LPos_target, LPos_domain, Stream),
   nl(Stream),
   nl(Stream),
   
   get_negative_examples(LNeg, LNeg_target, LNeg_domain),
   draw_the_examples(neg, P_neg, LNeg, LNeg_target, LNeg_domain, Stream),
   nl(Stream),
   nl(Stream),

   close(Stream).
   
  
get_positive_examples(LPos, LTarget, LDomain) :-
   findall(Ex, bk:pos(N,Ex), LPos),
   findall(Target, bk:target(N,Target), LTarget),
   findall(Domain, bk:domains(N,Domain), LDomain).
   
get_negative_examples(LNeg, LTarget, LDomain) :-
   findall(Ex, bk:neg(N,Ex), LNeg),
   findall(Target, bk:target(N,Target), LTarget),
   findall(Domain, bk:domains(N,Domain), LDomain).

 
	/* */
draw_the_examples(Signe, P, Lex, LTarget, LDomain, Stream) :-
   length(Lex, N_ex),
   N is round(P * N_ex/100.0),
   n_times(N),
   draw_an_example(N_ex, Lex, LTarget, LDomain, Ex, Target, Domain),
   write_example(Ex, Target, Domain, Signe, Stream),
   fail.
   
draw_the_examples(_Signe, _P, _Lex, _LTarget, _LDomain, _Stream). 


	/* draw an example in Lex */
draw_an_example(N, Lex, LTarget, LDomain, Ex, Target, Domain) :-
   randseq(1, N, [Index]),
   nth1(Index, Lex, Ex),
   nth1(Index, LTarget, Target),
   nth1(Index, LDomain, Domain).
   
   
/* write the current example */ 
write_example(Ex, Target, Domain, Signe, Stream) :-
  get_count(nb_examples, N),
  Term =..[Signe,N, Ex],
  fwrite_point_ln(Stream, Term),
  fwrite_point_ln(Stream, target(N, Target)),
  fwrite_point_ln(Stream, domains(N, Domain)),
  nl(Stream).
 
/* ============================== END OF LISTING ============================ */   
