void GeneticPopulation::speciate() {
        double compatThreshold = Globals::getSingleton()->getParameterValue("CompatibilityThreshold");

        for (int a = 0; a < generations[generations.size() - 1/*onGeneration*/]->getIndividualCount(); a++) {
            shared_ptr<GeneticIndividual> individual = generations[generations.size() - 1/*onGeneration*/]->getIndividual(a);

            bool makeNewSpecies = true;

            for (int b = 0; b < (int) species.size(); b++) {
                double compatibility = species[b]->getBestIndividual()->getCompatibility(individual);
                if (compatibility < compatThreshold) {
                    //Found a compatible species
                    individual->setSpeciesID(species[b]->getID());
                    makeNewSpecies = false;
                    break;
                }
            }

            if (makeNewSpecies) {
                //Make a new species.  The process of making a new speceis sets the ID for the individual.
                shared_ptr<GeneticSpecies> newSpecies(new GeneticSpecies(individual));
                species.push_back(newSpecies);
            }
        }

        int speciesTarget = int(Globals::getSingleton()->getParameterValue("SpeciesSizeTarget"));

        double compatMod;
        double CompatibilityModifierParamVal = Globals::getSingleton()->getParameterValue("CompatibilityModifier");

        if ((int) species.size() < speciesTarget) {
            compatMod = -CompatibilityModifierParamVal;
        } else if ((int) species.size() > speciesTarget) {
            compatMod = +CompatibilityModifierParamVal;
        } else {
            compatMod = 0.0;
        }

        if (compatThreshold < (fabs(compatMod) + 0.3) && compatMod < 0.0) {
            //This is to keep the compatibility threshold from going ridiculusly small.
            if (compatThreshold < 0.001)
                compatThreshold = 0.001;

            compatThreshold /= 2.0;
        } else if (compatThreshold < (compatMod + 0.3)) {
            compatThreshold *= 2.0;
        } else {
            compatThreshold += compatMod;
        }

        Globals::getSingleton()->setParameterValue("CompatibilityThreshold", compatThreshold);
    }
void updateWorld2()
{
	//for(int n = 0; n < P.N; ++n)
	//{
	
	int size = world.size();
	std::vector<species> filler(size);	
	std::vector< std::vector< species > > newWorld(size,filler);

	std::vector<int> index = indices;

	std::random_shuffle(index.begin(), index.end());
	
	for(std::vector<int>::iterator i = index.begin(); i != index.end(); ++i)
	{
	  int y = (*i) % world.size();
	  int x = (int)( (*i) / world.size());
	
		//species at x,y dies and gets replaced
		//with prob 1-m it is from within the local community
		if(uniform() < P.m) //migration
		{
			species migrant = getSpeciesFromMetaCommunity();
			newWorld[x][y] = migrant;
		}
		else //no migration, local reproduction
		{
			int otherX = x; int otherY = y;
			if(P.dispersalType == "Square") findParent_Square(otherX,otherY,x,y); //square
			else if(P.dispersalType == "Circle") findParent_Circle(otherX,otherY,x,y); //circle
//			else if(P.dispersalType == "Reflect") findParent_Reflect(otherX,otherY,x,y);
			else findParent_Circle(otherX,otherY,x,y);  //default


			newWorld[x][y] = world[otherX][otherY];
			if(uniform() < P.speciationRate) newWorld[x][y] = newSpecies();
		}
	}

	world = newWorld;
}
void updateWorld()
{
	for(int n = 0; n < (0.5*P.N); ++n)
	{
		//pick a random cell
		int x = random_number(P.sizeX);
		int y = random_number(P.sizeY);
		bool picked_viable = (bool)viable[x][y];
		while(picked_viable == false)
		{
			x = random_number(P.sizeX);
			y = random_number(P.sizeY);
			picked_viable = (bool)viable[x][y];
		}


		//species at x,y dies and gets replaced
		//with prob 1-m it is from within the local community
		if(uniform() < P.m) //migration
		{
			species migrant = getSpeciesFromMetaCommunity();
			world[x][y] = migrant;
		}
		else //no migration, local reproduction
		{
			int otherX = x; int otherY = y;
			if(P.dispersalType == "Square") findParent_Square(otherX,otherY,x,y); //square
			else if(P.dispersalType == "Circle") findParent_Circle(otherX,otherY,x,y); //circle
//			else if(P.dispersalType == "Reflect") findParent_Reflect(otherX,otherY,x,y);
			else findParent_Circle(otherX,otherY,x,y);  //default


			world[x][y] = world[otherX][otherY];
			reproduction[otherX][otherY]++;
			//world[x][y] = world[otherX][otherY];


			if(uniform() < P.speciationRate) world[x][y] = newSpecies();
		}
	}
}
void initializeMetaCommunity()
{
	int Jm = P.Jm;
	std::vector<int> abund(1,0);
	std::size_t nsp = 1;
	abund.push_back(1);
	//std::cout << "progress: " << "\t";
	(*(P.FORM))->add_systemLog("progress: \r\n");
	int disp = (int)(Jm * 0.1);
	for(int j = 1; j < Jm; ++j)
	{
		if(j % disp == 0)
		{
			int x = j / disp;

			std::ostringstream osstream;
			osstream << x;
			std::string str = osstream.str();
			str += "\r\n";
			(*(P.FORM))->add_systemLog(str);//std::cout << j / disp << "\t";
		}
		//std::cout.flush();
		double x = uniform();
		double val = P.theta / (P.theta + j -1);
		if(x < val)
		{
			nsp++;
			if(nsp > (abund.size()-1))
			{
				int dif = 1+nsp - abund.size();
				for(int k = 0; k < dif; ++k) abund.push_back(0);
				
			}
			
			abund[nsp] = 1;
		}
		else
		{
			int translate_to_abund = (int)((x * j)-1);
			//now find corresponding species
			std::size_t index = 0;
			while(index < abund.size())
			{
				translate_to_abund -= abund[index];
				if(translate_to_abund <= 0) break;

				index++;
			}

			abund[index] = abund[index] + 1;
		}
	}

	for(std::size_t i = 0; i < abund.size() ;++i)
	{
		species newS = newSpecies();
		newS.count = abund[i];

		metaCommunity.push_back(newS);
	}

	//remove all empty species
	std::vector<species> temp;
	for(std::vector<species>::iterator m = metaCommunity.begin(); m != metaCommunity.end(); ++m)
	{
		if((*m).count > 0) temp.push_back((*m));
	}
	metaCommunity = temp;

	std::sort(metaCommunity.begin(), metaCommunity.end(), sortSpeciesCount);
	//update fractions
	double cumsum = 0.0;
	for(std::vector<species>::iterator it = metaCommunity.begin(); it != metaCommunity.end(); ++it)
	{
		double add = 1.0 * (*it).count / Jm;
		cumsum += add;
		(*it).fraction = cumsum;		
	}
}
Ejemplo n.º 5
0
void importPhase(XML_Node& phase, ThermoPhase* th)
{
    // Check the the supplied XML node in fact represents a phase.
    if (phase.name() != "phase") {
        throw CanteraError("importPhase",
                           "Current const XML_Node named, " + phase.name() +
                           ", is not a phase element.");
    }

    // In this section of code, we get the reference to the phase XML tree
    // within the ThermoPhase object. Then, we clear it and fill it with the
    // current information that we are about to use to construct the object. We
    // will then be able to resurrect the information later by calling xml().
    th->setXMLdata(phase);

    // set the id attribute of the phase to the 'id' attribute in the XML tree.
    th->setID(phase.id());
    th->setName(phase.id());

    // Number of spatial dimensions. Defaults to 3 (bulk phase)
    if (phase.hasAttrib("dim")) {
        int idim = intValue(phase["dim"]);
        if (idim < 1 || idim > 3) {
            throw CanteraError("importPhase",
                               "phase, " + th->id() +
                               ", has unphysical number of dimensions: " + phase["dim"]);
        }
        th->setNDim(idim);
    } else {
        th->setNDim(3); // default
    }

    // Set equation of state parameters. The parameters are specific to each
    // subclass of ThermoPhase, so this is done by method setParametersFromXML
    // in each subclass.
    const XML_Node& eos = phase.child("thermo");
    if (phase.hasChild("thermo")) {
        th->setParametersFromXML(eos);
    } else {
        throw CanteraError("importPhase",
                           " phase, " + th->id() +
                           ", XML_Node does not have a \"thermo\" XML_Node");
    }

    VPStandardStateTP* vpss_ptr = 0;
    int ssConvention = th->standardStateConvention();
    if (ssConvention == cSS_CONVENTION_VPSS) {
        vpss_ptr = dynamic_cast <VPStandardStateTP*>(th);
        if (vpss_ptr == 0) {
            throw CanteraError("importPhase",
                               "phase, " + th->id() + ", was VPSS, but dynamic cast failed");
        }
    }

    // Add the elements.
    if (ssConvention != cSS_CONVENTION_SLAVE) {
        installElements(*th, phase);
    }

    // Add the species.
    //
    // Species definitions may be imported from multiple sources. For each one,
    // a speciesArray element must be present.
    vector<XML_Node*> sparrays = phase.getChildren("speciesArray");
    if (ssConvention != cSS_CONVENTION_SLAVE && sparrays.empty()) {
        throw CanteraError("importPhase",
                           "phase, " + th->id() + ", has zero \"speciesArray\" XML nodes.\n"
                           + " There must be at least one speciesArray nodes "
                           "with one or more species");
    }
    vector<XML_Node*> dbases;
    vector_int sprule(sparrays.size(),0);

    // Default behavior when importing from CTI/XML is for undefined elements to
    // be treated as an error
    th->throwUndefinedElements();

    // loop over the speciesArray elements
    for (size_t jsp = 0; jsp < sparrays.size(); jsp++) {
        const XML_Node& speciesArray = *sparrays[jsp];

        // If the speciesArray element has a child element
        //
        //   <skip element="undeclared">
        //
        // then set sprule[jsp] to 1, so that any species with an undeclared
        // element will be quietly skipped when importing species. Additionally,
        // if the skip node has the following attribute:
        //
        // <skip species="duplicate">
        //
        // then duplicate species names will not cause Cantera to throw an
        // exception. Instead, the duplicate entry will be discarded.
        if (speciesArray.hasChild("skip")) {
            const XML_Node& sk = speciesArray.child("skip");
            string eskip = sk["element"];
            if (eskip == "undeclared") {
                sprule[jsp] = 1;
            }
            string dskip = sk["species"];
            if (dskip == "duplicate") {
                sprule[jsp] += 10;
            }
        }

        // Get a pointer to the node containing the species definitions for the
        // species declared in this speciesArray element. This may be in the
        // local file containing the phase element, or may be in another file.
        XML_Node* db = get_XML_Node(speciesArray["datasrc"], &phase.root());
        if (db == 0) {
            throw CanteraError("importPhase()",
                               " Can not find XML node for species database: "
                               + speciesArray["datasrc"]);
        }

        // add this node to the list of species database nodes.
        dbases.push_back(db);
    }

    // Now, collect all the species names and all the XML_Node * pointers for
    // those species in a single vector. This is where we decide what species
    // are to be included in the phase. The logic is complicated enough that we
    // put it in a separate routine.
    std::vector<XML_Node*> spDataNodeList;
    std::vector<std::string> spNamesList;
    vector_int spRuleList;
    formSpeciesXMLNodeList(spDataNodeList, spNamesList, spRuleList,
                           sparrays, dbases, sprule);

    size_t nsp = spDataNodeList.size();
    if (ssConvention == cSS_CONVENTION_SLAVE && nsp > 0) {
        throw CanteraError("importPhase()", "For Slave standard states, "
            "number of species must be zero: {}", nsp);
    }
    for (size_t k = 0; k < nsp; k++) {
        XML_Node* s = spDataNodeList[k];
        AssertTrace(s != 0);
        if (spRuleList[k]) {
           th->ignoreUndefinedElements();
        }
        th->addSpecies(newSpecies(*s));
        if (vpss_ptr) {
            const XML_Node* const ss = s->findByName("standardState");
            std::string ss_model = (ss) ? ss->attrib("model") : "ideal-gas";
            unique_ptr<PDSS> kPDSS(newPDSS(ss_model));
            kPDSS->setParametersFromXML(*s);
            vpss_ptr->installPDSS(k, std::move(kPDSS));
        }
        th->saveSpeciesData(k, s);
    }

    // Done adding species. Perform any required subclass-specific
    // initialization.
    th->initThermo();

    // Perform any required subclass-specific initialization that requires the
    // XML phase object
    std::string id = "";
    th->initThermoXML(phase, id);
}