/* ========================================================================== */ 
/*                         SHUFFLE INTENSIONAL EXAMPLES                       */
/*                  (used in a context of a cross validation)                 */
/* ========================================================================== */

   /* create a file containing positive and negative examples */
shuffle(
                       File_in,  % file containing intensional examples
                       File_out  % file that will contain shuffled examples
       ) :- 
                          
   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),

   atom_concat(Lear, '/read_write_examples.pl', Read_write),
   use_module(Read_write),
   
   atom_concat(File_in, '.int', File_int),
   ex:consult(File_int),
   
   writeln('shuffle intensional ambiguous examples...'),
   shuffle_file(File_out),
   writeln('finished').
   
/* ========================= CREATING FILES ================================ */  

shuffle_file(File) :-

   init_randomize,
  
   atom_concat(File, '.int', File_out),
   open(File_out, write, Stream),
   
   fwrite_ln(Stream, ':- style_check(-discontiguous).'),
   nl(Stream),
   
   reset_count(nb_examples),
   
   get_positive_examples(LPos),
   random_permutation(LPos, LPos1),
   write_examples(LPos1, Stream),

   get_negative_examples(LNeg),
   random_permutation(LNeg, LNeg1),
   write_examples(LNeg1, Stream),

   close(Stream).
   

get_positive_examples(LPos) :-
   findall(
            (pos, Ex, Domains, Target), 
            (ex:pos(N,Ex), ex:target(N, Target), ex:domains(N, Domains)),
            LPos
           ).
   
get_negative_examples(LNeg) :-
   findall(
            (neg, Ex, Domains, Target), 
            (ex:neg(N,Ex), ex:target(N, Target), ex:domains(N, Domains)),
            LNeg
           ).
   
write_examples([], _Stream) :-
   !.

write_examples([Ex|LEx], Stream) :-
   write_one_example(Ex, Stream),
   write_examples(LEx, Stream).
      
      
	/* write the current example */ 
write_one_example((Signe, Ex, Domain, Target), 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 ============================ */   
