/*
population.h   Selah Lynch   July '04

Class Population:
For use with genetic algorithm program.
Holds a number of solutions and the problem they are trying to solve.
Can store the fitness of these solutions.
Has genetic algorithm functions for breeding population and Mutating the population.
Populations can be mixed throughout the computers, to do this a population
object must be declared on each and every computer.


needs mpi!
*/

#ifndef POPULATION_H
#define POPULATION_H

#include <fstream.h>
#include "solution.h"
#include "problem.h"

class Population{
 public:
  Population(int popsizearg, Problem& probarg);
  //make a new population of randomites
  //sets a different seed for each in population
  Population(Population& pop);
  //dissallowes copy constructor, this is a waste
  ~Population();

  void BreedAndReplace(int percent);
  //for fitnesses, each index corresponds to one of
  //the solutions, the one that has the same index
  //kill some and then make children

  void Mutate(int percent);
  //performs mutations one of three kinds, distributed evenly
  //percent can be over 100

  void MixPopulations();
  //mixes populations from different computers
  //must be called by all computers together!!!

  void SetFitness();

  Solution& GetSln(int index);
  //gives complete access to any solution

  Solution& BestSln();

  void Display(ostream& o);

  int GetPopSize();

  private:
  void SendSome(int howmany[], int* &buffer, int bufsize);
  void RecvSome(int howmany[], int* &buffer, int bufsize);
  //helper functions for Mix Pop

  void KillSome(int percent);
  //using the fitness provided and the percent to kill provided
  //pick ones to kill in a random tornament manner
  //mark ones killed

  //sometimes thigns are killed twice, so the percentage is less,
  //especially if its a high percent to start with

  void ReplaceWithChildren(); //just random
  //randomly pick amongst the alive population for parents
  //to make a child to replace each killed population member

  int BoolIndex(bool* boolarr, bool trueorfalse, int idx);
  //a helperfunction for ReplaceWithChildren()
  //when given an array of bools and a true or false target
  //and an index, it returns the actual index of what idx
  //would correspond to if only true(orfalse) indexes existed
  //assumes the size of bool arr is popsize

  Problem prob;

  Solution *sol;
  //the solutions in this population
  int popsize;
  int numpoints;

  double* fitnesses;
  bool fitnessset;

  bool* iskilled;
  int numkilled;

  int myrank, sizeofcluster;

  static void check(bool b, char* mess);

};






#endif
