public List <Individual> GenerateDescendants(Individual father, Individual mother) { Individual mutatedFather = MutateMember(father); Individual mutatedMother = MutateMember(mother); if (StaticOperations.ValidateIndividual(mutatedFather) == false) { throw new NotSupportedException(); } if (StaticOperations.ValidateIndividual(mutatedMother) == false) { throw new NotSupportedException(); } List <Individual> crossOverIndividuals = PMX(mutatedMother, mutatedFather); foreach (Individual individual in crossOverIndividuals) { if (StaticOperations.ValidateIndividual(individual) == false) { throw new NotSupportedException(); } } return(crossOverIndividuals); }
private void HandlePhysicsInput() { if (!Input.anyKey) { return; } // Dash if (Input.GetKey(KeyCode.Space)) { if (canDash) { Dash(StaticOperations.TargetUnitVec(body.position, cam.ScreenToWorldPoint(Input.mousePosition))); } } // Regular movement if (canMove) { Vector2 vec = GetMovementInput(); if (vec.magnitude > 0) { if (Input.GetKey(KeyCode.LeftShift) && SprintUpdate()) { // sprinting Move(vec, movementForce * 1.5f, sprintMaxVel); } else { Move(vec, movementForce, MAX_VEL); } } } }
public List <Representation> GenerateDescendants() { // We need as many descendants as we have parents // Parent count will be an even number // parents will be processed by sexual operator in pairs as they are ordered in the parents list List <Representation> descendants = new List <Representation>(descendantsPopulationCount); for (int i = 0; i < parents.Count; i = i + 2) { // Step 1: Both parents will undergo mutation separately Representation mutatedMother = MutateMember(parents[i]); if (StaticOperations.ValidateRepresentation(mutatedMother) == false) { throw new NotSupportedException(); } Representation mutatedFather = MutateMember(parents[i + 1]); if (StaticOperations.ValidateRepresentation(mutatedFather) == false) { throw new NotSupportedException(); } // Step 2: Attempt crossover for mutated parents List <Representation> children = CrossOverMembers(mutatedMother, mutatedFather); foreach (Representation representation in children) { if (StaticOperations.ValidateRepresentation(representation) == false) { throw new NotSupportedException(); } } descendants.AddRange(children); } return(descendants); }
public Initialisation(int populationCount, int scale) { this.populationCount = populationCount; this.scale = scale; random = new Random(); maximumHourChanges = StaticOperations.GenerateMaximumHourlyChanges(scale); }
public void RealizeEvolution() { Initialisation initialisation = new Initialisation(initialPopulationCount); // Initialisation - validated List <Path> population = initialisation.GenerateInitialPopulation(); for (int i = 0; i < population.Count; i++) { if (StaticOperations.ValidatePath(population[i]) == false) { throw new NotSupportedException(); } } // Evaluation Evaluation evaluation = new Evaluation(); evaluation.EvaluatePopulation(population); // Encoding List <Representation> representations = new List <Representation>(); Decoder decoder = new Decoder(); foreach (Path path in population) { Representation representation = decoder.EncodePath(path); representations.Add(representation); } // Evolution cycle for (int i = 0; i < evolutionCycles; i++) { // Selection Selection selection = new Selection(parentsCount, representations); List <Representation> parents = selection.SelectParents(); // Genetic operator - validated GeneticOperator geneticOperator = new GeneticOperator(descendantsCount, parents); List <Representation> descendants = geneticOperator.GenerateDescendants(); // Decoding List <Path> descendantPaths = new List <Path>(); foreach (Representation representation in descendants) { Path path = decoder.DecodeRepresentation(representation); if (StaticOperations.ValidatePath(path) == false) { throw new NotSupportedException(); } descendantPaths.Add(path); } // Evaluation evaluation.EvaluatePopulation(descendantPaths); for (int j = 0; j < descendants.Count; j++) { descendants[j].Fitness = descendantPaths[j].Fitness; } // Replacement Replacement replacement = new Replacement(parents, descendants, initialPopulationCount); representations = replacement.NextGeneration(); // Save to export file SaveTwoBestMembers(representations); } }
private List <Machine> RandomMachineHourScheduleGeneration(List <Machine> hour, int load) { List <int> stoppedMachines = Enumerable.Range(0, scale * 10).ToList(); // Turn on machines so that: // a) maximum achievable load is higher than demand // b) minimum achievable load is lower than demand // This allows random corrections to achieve exactly the value of load List <Machine> hourClone = StaticOperations.CloneMachineList(hour); int totalMaximumPower = 0; int totalMinimumPower = 0; while (true) { stoppedMachines.Shuffle(); int startingMachineIndex = stoppedMachines[0]; stoppedMachines.RemoveAt(0); hourClone[startingMachineIndex].CurrentOutputPower = hourClone[startingMachineIndex].MaximumOutputPower; totalMaximumPower += hourClone[startingMachineIndex].MaximumOutputPower; totalMinimumPower += hourClone[startingMachineIndex].MinimumOutputPower; if (totalMaximumPower >= load) { if (totalMinimumPower <= load) { break; } else { stoppedMachines = Enumerable.Range(0, scale * 10).ToList(); hourClone = StaticOperations.CloneMachineList(hour); } } } double totalLoad = totalMaximumPower; // Randomly reduce current power output to suffice power demand while (totalLoad > load) { List <int> adjustableMachineIndices = GetLowerableMachineIndices(hourClone); adjustableMachineIndices.Shuffle(); int index = adjustableMachineIndices[0]; double change = random.NextDouble() * (totalLoad - load); if (totalLoad - load < 1) { change = totalLoad - load; } double maximumAllowedChange = hourClone[index].CurrentOutputPower - hourClone[index].MinimumOutputPower; change = change > maximumAllowedChange ? maximumAllowedChange : change; hourClone[index].CurrentOutputPower -= change; totalLoad -= change; } return(hourClone); }
private void RestoreScheduleFromBackup(List <List <Machine> > schedule, List <List <Machine> > backup) { for (int i = 0; i < backup.Count; i++) { List <Machine> machineListClone = StaticOperations.CloneMachineList(backup[i]); schedule[i] = machineListClone; } }
public List <Individual> GenerateGroupInitialPopulation() { List <Individual> initialPopulation = new List <Individual>(); for (int i = 0; i < populationCount; i++) { List <List <Machine> > schedule = new List <List <Machine> >(24); for (int j = 0; j < 24; j++) { schedule.Add(StaticOperations.GenerateMachineTemplate(scale)); } List <int> initialState = StaticOperations.GenerateInitialMachinesState(scale); List <int> hourlyPowerDemand = StaticOperations.GenerateHourlyLoads(scale); maximumHourChanges = StaticOperations.GenerateMaximumHourlyChanges(scale); Group baseGroup = new Group(new List <int> { 0, 1 }); Group intermittentGroup = new Group(new List <int> { 2, 3, 4 }); Group semiPeakGroup = new Group(new List <int> { 5, 6 }); Group peakGroup = new Group(new List <int> { 7, 8, 9 }); List <Group> groups = new List <Group> { baseGroup, intermittentGroup, semiPeakGroup, peakGroup }; List <List <Machine> > scheduleBackup = BackupSchedule(schedule); schedule[0] = RandomMachineHourGrouppedScheduleInitialisation(schedule[0], groups, hourlyPowerDemand[0]); ReviseMachineStatus(schedule[0], initialState); for (int j = 1; j < 24; j++) { schedule[j] = RandomMachineHourGrouppedScheduleInitialisationWithReference(schedule[j], schedule[j - 1], groups, hourlyPowerDemand[j], out bool success); ReviseMachineStatus(schedule[j], schedule[j - 1]); if (success == false) { j = 0; RestoreScheduleFromBackup(schedule, scheduleBackup); schedule[0] = RandomMachineHourGrouppedScheduleInitialisation(schedule[0], groups, hourlyPowerDemand[0]); ReviseMachineStatus(schedule[0], initialState); } } Individual representation = new Individual(schedule) { groups = groups }; initialPopulation.Add(representation); } return(initialPopulation); }
public bool SifreHatirlat(string m) { var uye = _uyeDal.Get(x => x.Mail == m); if (uye != null) { return(StaticOperations.MailGonder(m, "Şifre Hatırlatma", "Şifreniz : " + uye.Sifre, false)); } return(false); }
private void RecalculateFitness(Representation reference) { // Recalculates fitness of members based on similarity criteria double weight = 0.4; foreach (Representation member in currentPopulation) { int distance = StaticOperations.TotalDistanceBetweenPaths(reference, member); // The higher the distance, the better double newFitness = member.Fitness * (weight + (1 - weight) * distance); member.CombinedFitness = newFitness; } }
private List <List <Machine> > BackupSchedule(List <List <Machine> > schedule) { List <List <Machine> > scheduleClone = new List <List <Machine> >(); foreach (List <Machine> hour in schedule) { List <Machine> hourClone = StaticOperations.CloneMachineList(hour); scheduleClone.Add(hourClone); } return(scheduleClone); }
private List <Individual> CrossOverIndividuals(Individual mutatedMother, Individual mutatedFather) { // Descendants are created by randomly switching a randomly generated amount of hours // Only corresponding hours may be switched and only when both individuals have the same machines running Individual fatherClone = Individual.CloneRepresentation(mutatedFather); Individual motherClone = Individual.CloneRepresentation(mutatedMother); Random random = new Random(); double chance = random.NextDouble(); for (int i = 0; i < fatherClone.Schedule.Count; i++) { double value = random.NextDouble(); if (value >= chance) { if (IsCrossOverApplicable(fatherClone.Schedule[i], motherClone.Schedule[i])) { List <Machine> temp = fatherClone.Schedule[i]; fatherClone.Schedule[i] = motherClone.Schedule[i]; motherClone.Schedule[i] = temp; } } } ReviseMachineStatus(fatherClone); ReviseMachineStatus(motherClone); List <Individual> descendants = new List <Individual>(); if (StaticOperations.ValidateIndividual(motherClone) == false) { descendants.Add(mutatedMother); } else { descendants.Add(motherClone); } if (StaticOperations.ValidateIndividual(fatherClone) == false) { descendants.Add(mutatedFather); } else { descendants.Add(fatherClone); } return(descendants); }
private void ReviseMachineStatus(Individual representation) { List <int> initialState = StaticOperations.GenerateInitialMachinesState(scale); // Calculate values of current machine states for (int i = 0; i < representation.Schedule.Count; i++) { List <int> referenceStates = null; if (i == 0) { referenceStates = initialState; } else { referenceStates = representation.Schedule[i - 1].Select(machine => machine.CurrentStatus).ToList(); } for (int j = 0; j < representation.Schedule[i].Count; j++) { Machine current = representation.Schedule[i][j]; if (current.CurrentOutputPower > 0) { // Machine was running in previous hour if (referenceStates[j] > 0) { current.CurrentStatus = referenceStates[j] + 1; } // Machine was turned off in previous hour if (referenceStates[j] < 0) { current.CurrentStatus = 1; } } if (current.CurrentOutputPower == 0) { // Machine was running in previous hour if (referenceStates[j] > 0) { current.CurrentStatus = -1; } if (referenceStates[j] < 0) { current.CurrentStatus = referenceStates[j] - 1; } } } } }
public List <Individual> NextGeneration() { List <Individual> newGeneration = new List <Individual>(); // Get elite 10% of old population List <Individual> orderedOldGeneration = oldGeneration.OrderBy(item => item.Fitness).ToList(); orderedOldGeneration.RemoveAll(item => StaticOperations.ValidateIndividual(item) == false); newGeneration.AddRange(orderedOldGeneration.Take(newGenerationCount / 10)); // Fill up remaining spots with descendants List <Individual> orderedDescendants = descendants.OrderBy(item => item.Fitness).ToList(); // Remove invalid descendants orderedDescendants.RemoveAll(item => StaticOperations.ValidateIndividual(item) == false); newGeneration.AddRange(orderedDescendants.Take(newGenerationCount - newGeneration.Count)); return(newGeneration); }
public List <Individual> GenerateDescendants(Individual mother, Individual father) { Individual mutatedMother = null; for (int i = 0; i < 5; i++) { mutatedMother = MutateIndividual(mother); if (StaticOperations.ValidateIndividual(mutatedMother)) { break; } } if (StaticOperations.ValidateIndividual(mutatedMother) == false) { mutatedMother = mother; } Individual mutatedFather = null; for (int i = 0; i < 5; i++) { mutatedFather = MutateIndividual(father); if (StaticOperations.ValidateIndividual(mutatedFather)) { break; } } if (StaticOperations.ValidateIndividual(mutatedFather) == false) { mutatedFather = father; } List <Individual> descendants = CrossOverIndividuals(mutatedMother, mutatedFather); if (StaticOperations.ValidateIndividual(descendants[0]) == false) { descendants[0] = mother; } if (StaticOperations.ValidateIndividual(descendants[1]) == false) { descendants[1] = father; } return(descendants); }
private GameObject FindNearestEnemyInSight() { int mask = 1 << 9; // Scan for enemies with enemy layer mask. Collider2D[] enemiesInRange = Physics2D.OverlapCircleAll( new Vector2(transform.position.x, transform.position.y), light2d.pointLightOuterRadius, mask); Collider2D closestEnemy = StaticOperations.DetermineClosestCollider(enemiesInRange, new Vector2(transform.position.x, transform.position.y)); if (closestEnemy == null) { return(null); } return(closestEnemy.gameObject); }
public List <Individual> GenerateDescendants(Individual mother, Individual father) { Individual motherClone = Individual.CloneIndividual(mother); Individual fatherClone = Individual.CloneIndividual(father); double value = random.NextDouble(); Individual mutatedMother = null, mutatedFather = null; int counter = 0; for (int i = 0; i < 5; i++) { mutatedMother = MutateIndividual(motherClone); if (StaticOperations.ValidateIndividual(mutatedMother)) { break; } counter++; } if (counter == 5) { mutatedMother = mother; } counter = 0; for (int i = 0; i < 5; i++) { mutatedFather = MutateIndividual(fatherClone); if (StaticOperations.ValidateIndividual(mutatedFather)) { break; } counter++; } if (counter == 5) { mutatedFather = father; } List <Individual> crossedOvers = CrossOverIndividuals(mutatedMother, mutatedFather); return(crossedOvers); }
public List <Individual> GenerateInitialPopulation() { List <Individual> initialPopulation = new List <Individual>(); for (int i = 0; i < populationCount; i++) { List <List <Machine> > schedule = new List <List <Machine> >(24); for (int j = 0; j < 24; j++) { schedule.Add(StaticOperations.GenerateMachineTemplate(scale)); } List <int> initialState = StaticOperations.GenerateInitialMachinesState(scale); List <int> hourlyPowerDemand = StaticOperations.GenerateHourlyLoads(scale); List <int> maximumHourlyChanges = StaticOperations.GenerateMaximumHourlyChanges(scale); List <List <Machine> > scheduleBackup = BackupSchedule(schedule); // 1.) Randomly generate first hour schedule schedule[0] = RandomMachineHourScheduleGeneration(schedule[0], hourlyPowerDemand[0]); ReviseMachineStatus(schedule[0], initialState); for (int j = 1; j < 24; j++) { schedule[j] = RandomMachineHourScheduleGenerationWithReference(schedule[j - 1], hourlyPowerDemand[j], out bool success); ReviseMachineStatus(schedule[j], schedule[j - 1]); if (success == false) { j = 0; RestoreScheduleFromBackup(schedule, scheduleBackup); schedule[0] = RandomMachineHourScheduleGeneration(schedule[0], hourlyPowerDemand[0]); double hourPower = schedule[0].Sum(item => item.CurrentOutputPower); ReviseMachineStatus(schedule[0], initialState); } } Individual representation = new Individual(schedule); initialPopulation.Add(representation); Console.WriteLine("Initial population count: " + i); } return(initialPopulation); }
public List <Individual> GenerateDescendants(Individual mother, Individual father) { Individual motherClone = Individual.CloneRepresentation(mother); Individual fatherClone = Individual.CloneRepresentation(father); Individual mutatedMother = MutateIndividual(motherClone); Individual mutatedFather = MutateIndividual(fatherClone); if (StaticOperations.ValidateIndividual(mutatedMother) == false) { mutatedMother = Individual.CloneRepresentation(mother); } if (StaticOperations.ValidateIndividual(mutatedFather) == false) { mutatedFather = Individual.CloneRepresentation(father); } List <Individual> descendants = CrossOverIndividuals(mutatedMother, mutatedFather); return(descendants); }
public static void DecoderTesting() { List <Point> references = new List <Point>(); Point reference = new Point(3, 21); references.Add(reference); reference = new Point(29, 7); references.Add(reference); reference = new Point(6, 27); references.Add(reference); reference = new Point(8, 18); references.Add(reference); reference = new Point(28, 9); references.Add(reference); reference = new Point(14, 11); references.Add(reference); reference = new Point(9, 13); references.Add(reference); reference = new Point(31, 14); references.Add(reference); reference = new Point(30, 23); references.Add(reference); reference = new Point(23, 25); references.Add(reference); reference = new Point(20, 15); references.Add(reference); reference = new Point(11, 17); references.Add(reference); reference = new Point(27, 12); references.Add(reference); reference = new Point(12, 5); references.Add(reference); reference = new Point(30, 11); references.Add(reference); Individual individual = new Individual(references); bool status = StaticOperations.ValidateIndividual(individual); }
public Uye GetByCookie(string cookUye) { return(_uyeDal.Get(x => StaticOperations.Md5Creator(x.Mail + "-" + x.Sifre) == cookUye)); }
private Individual MutateIndividual(Individual individual) { Individual individualClone = Individual.CloneRepresentation(individual); // Every hour needs to be mutated separately // after mutating one of the hours, values for // turned on time on machines need to be revised // Revision is needed only if start/terminate operators are used Random random = new Random(); for (int i = 0; i < individualClone.Schedule.Count; i++) { double mutationChange = random.NextDouble(); if (mutationChange <= 0.25) { int mutationEffect = random.Next(0, 3); // Increase mutation if (mutationEffect == 0) { individualClone.Schedule[i] = IncreaseMutation(individualClone.Schedule[i], i == 0 ? null : individualClone.Schedule[i - 1], random); if (StaticOperations.ValidateIndividual(individualClone) == false) { individualClone.Schedule[i] = StaticOperations.CloneMachineList(individual.Schedule[i]); } } // Decrease mutation if (mutationEffect == 1) { individualClone.Schedule[i] = DecreaseMutation(individualClone.Schedule[i], i == 0 ? null : individualClone.Schedule[i - 1], random); if (StaticOperations.ValidateIndividual(individualClone) == false) { individualClone.Schedule[i] = StaticOperations.CloneMachineList(individual.Schedule[i]); } } // Start mutation if (mutationEffect == 2) { individualClone.Schedule[i] = StartMutation(individualClone.Schedule[i], i == 0 ? null : individualClone.Schedule[i - 1], random); if (StaticOperations.ValidateIndividual(individualClone) == false) { individualClone.Schedule[i] = StaticOperations.CloneMachineList(individual.Schedule[i]); } ReviseMachineStatus(individualClone); } // Terminate mutation if (mutationEffect == 3) { individualClone.Schedule[i] = TerminateMutation(individualClone.Schedule[i], i == 0 ? null : individualClone.Schedule[i - 1], random); if (StaticOperations.ValidateIndividual(individualClone) == false) { individualClone.Schedule[i] = StaticOperations.CloneMachineList(individual.Schedule[i]); } ReviseMachineStatus(individualClone); } } } return(individualClone); }
private List <Machine> TerminateMutation(List <Machine> hourSchedule, List <Machine> previous, Random random) { // Terminates randomly chosen running machine List <Machine> machineListClone = StaticOperations.CloneMachineList(hourSchedule); // Get indices of currently running machines List <int> terminatableMachinesIndices = GetTerminatableMachineIndices(hourSchedule); if (terminatableMachinesIndices.Count == 0) { return(hourSchedule); } terminatableMachinesIndices.Shuffle(); int terminateIndex = terminatableMachinesIndices[0]; double change = machineListClone[terminateIndex].CurrentOutputPower; machineListClone[terminateIndex].CurrentOutputPower = 0; List <int> runningMachinesIndices = GetRunningMachineIndices(machineListClone); // Try increasing power of other machines to compensate change double load = hourSchedule.Sum(item => item.CurrentOutputPower); while (change > 0) { List <int> incresableMachineIndices = GetIncreasableMachineIndices(machineListClone, previous, maximumHourlyChange); if (incresableMachineIndices.Count > 0) { // Randomise indices incresableMachineIndices.Shuffle(); int index = incresableMachineIndices[0]; double maximumAllowedIncrease; if (previous != null) { maximumAllowedIncrease = GetMaximumMachineIncrease(machineListClone[index], previous[index], maximumHourlyChange[index]); } else { maximumAllowedIncrease = GetMaximumMachineIncrease(machineListClone[index], null, maximumHourlyChange[index]); } // If machine can fully compensate power increase, it will be used to do it if (maximumAllowedIncrease > change) { machineListClone[index].CurrentOutputPower += change; } // If not, its power is reduced to minimum output power else { machineListClone[index].CurrentOutputPower += maximumAllowedIncrease; } change = load - machineListClone.Sum(item => item.CurrentOutputPower); } else { break; } } // If change was fully compensated, mutation was finished if (change == 0) { return(machineListClone); } // If change was not fully compensated, mutation failed else { return(hourSchedule); } }
private List <Machine> StartMutation(List <Machine> hourSchedule, List <Machine> previous, Random random) { // Starts a random machine that is allowed to be started // with minimum output power List <Machine> machineListClone = StaticOperations.CloneMachineList(hourSchedule); List <int> startableMachineIndices = GetStartableMachineIndices(hourSchedule); // If not startable machines are found, operator is not applicable if (startableMachineIndices.Count == 0) { return(hourSchedule); } startableMachineIndices.Shuffle(); // Randomly pick one of the startable machines and start if with minimum power output int startIndex = startableMachineIndices[0]; machineListClone[startIndex].CurrentOutputPower = machineListClone[startIndex].MinimumOutputPower; double change = machineListClone[startIndex].CurrentOutputPower; // Get currently running machines List <int> runningMachinesIndices = GetRunningMachineIndices(machineListClone); runningMachinesIndices.Remove(startIndex); // Power produced by newly started machine needs to be compensated double load = hourSchedule.Sum(item => item.CurrentOutputPower); while (change > 0) { List <int> lowerableMachineIndices = GetLowerableMachineIndices(machineListClone, previous, maximumHourlyChange); if (lowerableMachineIndices.Count > 0) { // Randomise indices lowerableMachineIndices.Shuffle(); int index = lowerableMachineIndices[0]; double maximumAllowedDecrease; if (previous != null) { maximumAllowedDecrease = GetMaximumMachineDecrease(machineListClone[index], previous[index], maximumHourlyChange[index]); } else { maximumAllowedDecrease = GetMaximumMachineDecrease(machineListClone[index], null, maximumHourlyChange[index]); } // If machine can fully compensate power increase, it will be used to do it if (maximumAllowedDecrease > change) { machineListClone[index].CurrentOutputPower -= change; } // If not, its power is reduced as much as possible else { machineListClone[index].CurrentOutputPower -= maximumAllowedDecrease; } change = machineListClone.Sum(item => item.CurrentOutputPower) - load; } else { break; } } // If change was fully compensated, mutation was finished if (change == 0) { return(machineListClone); } // If change was not fully compensated, mutation failed else { return(hourSchedule); } }
private List <Machine> DecreaseMutation(List <Machine> hourSchedule, List <Machine> previous, Random random) { // Decreases value of a randomly chosen running machine List <Machine> machineListClone = StaticOperations.CloneMachineList(hourSchedule); // Get currently running machines List <int> runningMachinesIndices = GetRunningMachineIndices(hourSchedule); // Randomly pick one running machine and generate chagne value int mutationIndex = runningMachinesIndices[random.Next(0, runningMachinesIndices.Count)]; double maximumAllowedDecrease; if (previous != null) { maximumAllowedDecrease = GetMaximumMachineDecrease(hourSchedule[mutationIndex], previous[mutationIndex], maximumHourlyChange[mutationIndex]); } else { maximumAllowedDecrease = GetMaximumMachineDecrease(hourSchedule[mutationIndex], null, maximumHourlyChange[mutationIndex]); } double change = random.NextDouble() * maximumAllowedDecrease; // Decrease power value of selected machine machineListClone[mutationIndex].CurrentOutputPower -= change; // If machine with lowest power was chosen, no changes can be made if (change == 0) { return(hourSchedule); } // Try increasing power of other machines to compensate the change double load = hourSchedule.Sum(item => item.CurrentOutputPower); while (change > 0) { List <int> incresableMachineIndices = GetIncreasableMachineIndices(machineListClone, previous, maximumHourlyChange); incresableMachineIndices.Remove(mutationIndex); if (incresableMachineIndices.Count > 0) { // Randomise indices incresableMachineIndices.Shuffle(); int index = incresableMachineIndices[0]; double maximumAllowedIncrease; if (previous != null) { maximumAllowedIncrease = GetMaximumMachineIncrease(machineListClone[index], previous[index], maximumHourlyChange[index]); } else { maximumAllowedIncrease = GetMaximumMachineIncrease(machineListClone[index], null, maximumHourlyChange[index]); } // If machine can fully compensate power increase, it will be used to do it if (maximumAllowedIncrease > change) { machineListClone[index].CurrentOutputPower += change; } // If not, its power is reduced to minimum output power else { machineListClone[index].CurrentOutputPower += maximumAllowedIncrease; } change = load - machineListClone.Sum(item => item.CurrentOutputPower); } else { break; } } // If change was fully compensated, mutation was finished if (change == 0) { return(machineListClone); } // If change was not fully compensated, mutation failed else { return(hourSchedule); } }
public GeneticOperators(int scale) { this.scale = scale; maximumHourlyChange = StaticOperations.GenerateMaximumHourlyChanges(scale); }
public void RealizeEvolution() { Random random = new Random(); Initialisation initialisation = new Initialisation(initialPopulationCount); // Initialisation - validated List <Path> population = initialisation.GenerateInitialPopulation(); for (int i = 0; i < population.Count; i++) { if (StaticOperations.ValidatePath(population[i]) == false) { throw new NotSupportedException(); } } // Evaluation Evaluation evaluation = new Evaluation(); evaluation.EvaluatePopulation(population); // Encoding List <Representation> representations = new List <Representation>(); Decoder decoder = new Decoder(); foreach (Path path in population) { Representation representation = decoder.EncodePath(path); representations.Add(representation); } // Evolution cycle for (int i = 0; i < evolutionCycles; i++) { Console.Write("Epoch #" + i + "."); // Reinitialisation happens every 1/10th iteration and randomly resets half of population // Elite 10% is untouched by this process if ((i % 500) == 0 && i != 0) { ReinitializePopulation(representations, (int)(3 * initialPopulationCount / 4)); } // Remap fitness using exponential remapping //RemapFitness(representations, remapParameter); // Selection Selection selection = new Selection(parentsCount, representations); List <Representation> parents = selection.SelectParents(); //List<Representation> parents = selection.SelectCombinedParents(); // Genetic operator - validated GeneticOperator geneticOperator = new GeneticOperator(descendantsCount, parents); List <Representation> descendants = geneticOperator.GenerateDescendants(); // Decoding List <Path> descendantPaths = new List <Path>(); foreach (Representation representation in descendants) { Path path = decoder.DecodeRepresentation(representation); if (StaticOperations.ValidatePath(path) == false) { throw new NotSupportedException(); } descendantPaths.Add(path); } // Evaluation evaluation.EvaluatePopulation(descendantPaths); for (int j = 0; j < descendants.Count; j++) { descendants[j].Fitness = descendantPaths[j].Fitness; } // Revaluate current population after fitness remapping //List<Path> currentPaths = new List<Path>(); //foreach (Representation representation in representations) //{ // Path path = decoder.DecodeRepresentation(representation); // currentPaths.Add(path); //} //evaluation.EvaluatePopulation(currentPaths); //for (int j = 0; j < representations.Count; j++) //{ // representations[j].Fitness = currentPaths[j].Fitness; //} // Replacement Replacement replacement = new Replacement(representations, descendants, initialPopulationCount); //representations = replacement.GenerationReplacement(); //representations = replacement.NextGeneration(); representations = replacement.DuplicationElimination(7, representations.Count / 20 < 3 ? representations.Count / 20 : 3, 20); Console.Write(" Maximum fitness: " + representations.Max(item => item.Fitness)); // Save to export file SaveSixBestMembers(representations); } }
private void SaveBestIndividualIntoFile(Individual representation) { FileStream memoryStream = new FileStream("riesenie.pdf", FileMode.OpenOrCreate, FileAccess.Write); Document document = new Document(PageSize.A4, 10, 10, 10, 10); PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); document.Open(); PdfPTable table = new PdfPTable(10 * scale + 2) { SpacingBefore = 3, SpacingAfter = 3, HorizontalAlignment = Element.ALIGN_LEFT }; Font font6 = FontFactory.GetFont(FontFactory.TIMES, BaseFont.CP1250, BaseFont.EMBEDDED, 6f); Font boldFont6 = FontFactory.GetFont(FontFactory.TIMES_BOLD, BaseFont.CP1250, BaseFont.EMBEDDED, 6f); List <float> widths = new List <float>(); for (int i = 0; i < scale; i++) { for (int j = 0; j < 10; j++) { widths.Add(60f); } } widths.AddRange(new List <float> { 60f, 60f }); table.SetWidths(widths.ToArray()); // Row 1 PdfPCell cell11 = CreateAlignedCell("S.No", boldFont6); cell11.Rowspan = 2; table.AddCell(cell11); PdfPCell cell12 = CreateAlignedCell("Load \n (MW)", boldFont6); cell12.Rowspan = 2; table.AddCell(cell12); PdfPCell cell13 = CreateAlignedCell("Commitment schedule", font6); cell13.Colspan = 10 * scale; table.AddCell(cell13); // Row 2 for (int i = 1; i < 1 + 10 * scale; i++) { PdfPCell numberCell = CreateAlignedCell(i + "", boldFont6); table.AddCell(numberCell); } // Row 3 - 26 List <int> hourlyLoads = StaticOperations.GenerateHourlyLoads(scale); for (int i = 1; i < 25; i++) { PdfPCell iteratorCell = CreateAlignedCell(i + "", font6); table.AddCell(iteratorCell); PdfPCell loadCell = CreateAlignedCell(hourlyLoads[i - 1] + "", font6); table.AddCell(loadCell); for (int j = 0; j < representation.Schedule[i - 1].Count; j++) { PdfPCell unitCell = CreateAlignedCell( String.Format("{0:0.#}", representation.Schedule[i - 1][j].CurrentOutputPower), font6); table.AddCell(unitCell); } } document.Add(table); Paragraph paragraph = new Paragraph("Total operating cost: " + representation.Fitness + "$.") { SpacingBefore = 3, SpacingAfter = 3, Font = FontFactory.GetFont(FontFactory.TIMES, 9, BaseColor.BLACK), Alignment = 0 }; document.Add(paragraph); if (representation.groups != null) { int counter = 0; foreach (Group group in representation.groups) { counter++; StringBuilder builder = new StringBuilder(); builder.Append("Group " + counter + ": "); foreach (int machine in group.grouppedMachines) { builder.Append((machine + 1) + ", "); } string final = builder.ToString().TrimEnd(' ').TrimEnd(','); Paragraph groupParagraph = new Paragraph(final) { SpacingBefore = 3, SpacingAfter = 3, Font = FontFactory.GetFont(FontFactory.TIMES, 9, BaseColor.BLACK), Alignment = 0 }; document.Add(groupParagraph); } } document.Close(); memoryStream.Close(); }
public void RealiseGroupEvolution() { // Initialisation GroupInitialisation initialisation = new GroupInitialisation(initialPopulationCount, scale); List <Individual> population = null; if (mode == 1) { population = initialisation.GenerateGroupInitialPopulation(); } if (mode == 2) { population = initialisation.GenerateRandomGroupInitialPopulation(); } // Validation foreach (Individual representation in population) { if (StaticOperations.ValidateIndividualWithGroups(representation) == false) { throw new NotSupportedException(); } } // Evaluation Evaluation evaluation = new Evaluation(scale); foreach (Individual representation in population) { evaluation.EvaluateIndividual(representation); } // Evolution cycles for (int i = 0; i < evolutionCycles; i++) { Console.Write("Epoch #" + i + " "); // Selection Selection selection = new Selection(initialPopulationCount, population); List <Individual> parents = null; if (mode == 1) { parents = selection.SelectParents(2); } if (mode == 2) { parents = selection.SelectDiverseParents(2, 5); } // Genetic operators List <Individual> descendants = new List <Individual>(); GroupGeneticOperators geneticOperators = new GroupGeneticOperators(scale); for (int j = 0; j < parents.Count; j = j + 2) { descendants.AddRange(geneticOperators.GenerateDescendants(parents[j], parents[j + 1])); } // Evaluation foreach (Individual representation in descendants) { evaluation.EvaluateIndividual(representation); } // Replacement Replacement replacement = new Replacement(population, descendants, initialPopulationCount); population = replacement.NextGeneration(); List <Individual> orderedPopulation = population.OrderBy(item => item.Fitness).ToList(); Console.WriteLine("Best individual has fitness: " + orderedPopulation[0].Fitness); } SaveBestIndividualIntoFile(population[0]); }
public void RegenStamina(float amount) { stamina += StaticOperations.GetAdjustedIncrease(stamina, amount, MAX_STAMINA); UpdateStamina(); }