void Start() { bestCreatureController = FindObjectOfType <BestCreaturesController>(); cameraFollowController = FindObjectOfType <CameraFollowController>(); evolution = FindObjectOfType <Evolution>(); evolutionOverlayView.Delegate = this; bestCreatureOverlayView.Delegate = this; sharedOverlayView.Delegate = this; visibilityOptionsView.Delegate = this; evolution.NewBatchDidBegin += delegate() { Refresh(); }; evolution.SimulationWasSaved += delegate() { sharedOverlayView.ShowSuccessfulSaveAlert(); }; bestCreatureController.PlaybackDidBegin += delegate() { Refresh(); }; evolution.InitializationDidEnd += delegate() { if (!Settings.DontShowV2SimulationDeprecationOverlayAgain && evolution.SimulationData.LastV2SimulatedGeneration > 0) { v2PlaybackNoticePopup.Show(); } }; }
private void _miRemoveDrop_Click <TCollection>(object sender, RoutedEventArgs e, RangeListView lv) { if (lv.SelectedItems.Count <= 0 || _tab.List.SelectedItem == null) { return; } TValue item = (TValue)_tab.List.SelectedItem; var btable = _tab.Table; btable.Commands.Begin(); try { _removeSelected <TCollection>(lv); _evolution = new Evolution(); foreach (var targetEv in _lv.Items.OfType <PetEvolutionView>()) { if (targetEv == _lv.SelectedItem) { targetEv.EvolutionTarget.ItemRequirements = _lvRequirements.Items.OfType <PetEvolutionTargetView>().Select(requirement => requirement.Requirement).ToList(); } _evolution.Targets.Add(targetEv.EvolutionTarget); } btable.Commands.Set(item, ServerPetAttributes.Evolution, _evolution.ToString()); } catch (Exception err) { ErrorHandler.HandleException(err); } btable.Commands.EndEdit(); }
// Start is called before the first frame update void Start() { Evolution first = new Evolution(2, 1, 1, 0, 50, 0, 0); Evolution second = new Evolution(1, 2, 0, 0, 50, 0, 0); skills.Add(first); skills.Add(second); skills.Add(new Evolution(5, 5, 0, 0, 70, 10, 0)); skills.Add(new Evolution(0, 0, 2, 2, 90, 20, 0)); skills.Add(new Evolution(5, 2, 0, 5, 10, 50, 10)); skills.Add(new Evolution(2, 8, 2, 0, 20, 50, 5)); skills.Add(new Evolution(0, 0, 6, 5, 80, 20, 10)); skills.Add(new Evolution(8, 5, 0, 0, 50, 50, 0)); skills.Add(new Evolution(5, 2, 0, 5, 10, 50, 10)); skills.Add(new Evolution(2, 8, 2, 0, 20, 50, 5)); skills.Add(new Evolution(10, 2, 0, 5, 100, 30, 10)); skills.Add(new Evolution(2, 10, 5, 0, 100, 30, 15)); skills.Add(new Evolution(8, 12, 10, 1, 150, 20, 10)); skills.Add(new Evolution(9, 12, 2, 15, 200, 50, 0)); }
override public void Remove(uint amount_) { if (Amount() == 0 || amount_ == 0) { return; } var evolution = new Evolution() { Previous = amount }; if (amount_ >= amount) { evolution.Removed = amount; amount = 0; } else { evolution.Removed = amount_; amount -= amount_; } evolution.Current = amount; _Changed(evolution); }
override public void Add(uint amount_) { if (amount_ == 0) { return; } var evolution = new Evolution() { Previous = amount, Added = amount_ }; amount += amount_; groups.Add(new Grouped() { expiration = scheduler.Now + duration(), amount = amount_ }); scheduler.Start(Update, ref groups.Last().coroutine); if (maxAmount() > 0 && amount > maxAmount()) { evolution.Removed = amount - maxAmount(); RemoveFromGroups(evolution.Removed); } evolution.Current = amount; _Changed(evolution); }
private void OnCollisionEnter(Collision col) { if (col.gameObject.tag == "Sword" && Sinka_flg == true) { Transform wgbar = col.transform.Find("sword1Canvas/WGbar"); evolution = wgbar.gameObject.GetComponent <Evolution>(); evolution.Set_wgslider(20); evolution.Set_Wg(20); deathKnight = parent.gameObject.GetComponent <DeathKnight>(); deathKnight.Die(); Destoy(this); } if (col.gameObject.tag == "Sword" && Sinka_flg1 == true) { Transform Wgbar1 = col.transform.Find("sword2Canvas/Wgbar1"); evolution1 = Wgbar1.gameObject.GetComponent <Evolution1>(); evolution1.Set_wgslider1(20); evolution1.Set_Wg1(20); deathKnight = parent.gameObject.GetComponent <DeathKnight>(); deathKnight.Die(); Destoy(this); } if (col.gameObject.tag == "Sword" && Sinka_flg2 == true) { deathKnight = parent.gameObject.GetComponent <DeathKnight>(); deathKnight.Die(); Destoy(this); } }
public string evolucionUsu() { List <Evolution> datos = new List <Evolution>(); Usuario usuario = (Usuario)Session["infoUsuario"]; var collection = _dbContext.GetDatabase().GetCollection <Usuario>("usuarios"); var usuCollection = collection.AsQueryable().Where(x => x._id == usuario._id).FirstOrDefault(); string yearActual = DateTime.Today.Year.ToString(); foreach (var dicAnyos in usuCollection.EvolutionUser) { if (dicAnyos.Key.Equals(yearActual)) { foreach (var mes in dicAnyos.Value) { Evolution ev = new Evolution(); ev.Mes = mes.Key; ev.Puntos = mes.Value; datos.Add(ev); } } } return(JsonConvert.SerializeObject(datos)); }
IEnumerator Update() { yield return(scheduler.WaitUntil(expiration - (Amount() - 1) * duration())); coroutine = null; var evolution = new Evolution() { Previous = Amount() }; if (Amount() == 1) { yield break; } else if (Amount() == 1) { evolution.Removed = 1; amount = 0; expiration = 0; } else if (Amount() > 1) { evolution.Removed = 1; amount -= 1; expiration = scheduler.Now + duration() * Amount(); scheduler.Start(Update, ref coroutine); } evolution.Current = amount; _Changed(evolution); }
private void OnShipFinished(float score, int index) { finishedShips++; finishedBatchShips++; scores[index] = score; if (finishedBatchShips >= shipsPerBatch) { EndBatch(); currentBatch++; if (currentBatch >= batches) { currentGeneration++; chart.AddGenerationData(currentGeneration, GetMaxScore(), GetAvgScore()); if (currentGeneration < generations) { NewGeneration(); } else { DelimitedWriter.Write(Application.dataPath + "/trained.csv", Evolution.GetFittestChromosome(chromosomes, scores).ToColumnMatrix(), ",", null, null, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); SceneManager.LoadScene("Playing"); } } else { StartBatch(); } } }
public void FindsSimpleSolution() { var random = new SystemRandom(42); var factory = new SimpleGenomeFactory(random); var selection = new BinaryTournamentSelection(random); Environment environment = new SimpleEnvironment(); Ranking ranking = new CrowdingDistanceRanking(1); var evolution = new Evolution(100, 0.4, 0.4, factory, selection); var genomes = evolution.Initialize(); double score = 0; for (int i = 0; i < 100; i++) { // evaluate var population = genomes.Select(environment.Evaluate).ToList(); // rank ranking.Rank(population); // keep score var best = population[0]; Console.WriteLine(best); score = best.GetScore(0); // evolve genomes = evolution.Evolve(population, random); } Assert.Greater(score, 30); }
static void Main(string[] args) { var rules = new SelectiveMating(); var evolution = new Evolution(rules); evolution.RunEvolution(); }
private void Start() { //if (evolution == null) return; mateSprite.sprite = Util.RandomFromArray(mateSpriteOptions); evolution = new Evolution(); evolution.GenerateEvolution(); titleTxt.SetText(""); // Evo Name"); hpTxt.SetText(AddPlus(evolution.hp)); spTxt.SetText(AddPlus(evolution.sp)); strTxt.SetText(AddPlus(evolution.str)); agiTxt.SetText(AddPlus(evolution.agi)); if (evolution.action != null) { actionTxt.SetText(evolution.action.abilityName); } else { actionTxt.SetText(""); } if (evolution.trait != null) { traitTxt.SetText(evolution.trait.abilityName); } else { traitTxt.SetText(""); } }
public int luc; // Luck public static int getEvolution(Evolution [] e, Simple_Creature c) { int[] match = new int[e.Length]; for (int i = 0; i < e.Length; i++) { Evolution evo = e[i]; if ((c.age >= evo.age) && (c.pow_stat >= evo.pow) && (c.run_stat >= evo.run) && (c.swm_stat >= evo.swm) && (c.fly_stat >= evo.fly) && (c.sta_stat >= evo.sta) && (c.int_stat >= evo.intel) && (c.luc_stat >= evo.luc) ) { match[i] = 1; } //Now pick a match } for (int i = 0; i < match.Length; i++) { if (match[i] == 1) { return(e[i].id); } } return(-1); }
/* This method will return the species ID of whatever the passed creature can evolve into*/ public static void CheckEvolve(Simple_Creature c) { string path = "Assets/Resources/Creatures.json"; string data = File.ReadAllText(path); // TextAsset file = (TextAsset)Resources.Load("Creatures"); Debug.Log(data); //gets the table Creature [] j = new Creature[3]; j[0] = new Creature(0, "egg"); j[1] = new Creature(1, "nerd"); j[2] = new Creature(2, "test"); string jArray = JsonHelper.ToJson(j); Debug.Log(jArray); j = JsonHelper.FromJson <Creature>(data); Debug.Log(j[c.species_id].evolution.Length); Evolution[] possibles = j[c.species_id].evolution; //Check through evolutions to see if it satisfys any int toEvolve = Evolution.getEvolution(possibles, c); //If evolution found if (toEvolve != -1) { c.species_id = j[toEvolve].id; c.species = j[toEvolve].species; } }
public EDSCategory(Evolution.Source source) { this.name = source.Name; this.uid = source.Uid; this.taskList = new Cal (source, CalSourceType.Todo); this.isSystem = (string.Compare (source.RelativeUri, "system") == 0); }
/// <summary> /// Look recursively for probability (PROBnn) attributes and embed a new evolution object one level deeper for each /// </summary> /// <param name="evolution"></param> /// <param name="remaining_evo"></param> /// <param name="decodedTaf"></param> /// <returns></returns> private string ProbabilityChunkDecoder(Evolution evolution, string chunk, DecodedTaf decodedTaf) { var found = Regex.Matches(chunk, ProbabilityPattern).Cast <Match>().ToList(); if (found.Count < 1) { return(chunk); } var probability = found[0].Groups[1].Value.Trim(); var type = found[0].Groups[2].Value.Trim(); var period = found[0].Groups[3].Value.Trim(); var remaining = found[0].Groups[4].Value.Trim(); if (probability.StartsWith("PROB")) { evolution.Probability = probability; var embeddedEvolutionPeriodArray = period.Split('/'); var embeddedEvolution = new Evolution() { Type = !string.IsNullOrEmpty(type) ? type : Probability, FromDay = Convert.ToInt32(embeddedEvolutionPeriodArray[0].Substring(0, 2)), FromTime = embeddedEvolutionPeriodArray[0].Substring(2, 2) + ":00 UTC", ToDay = Convert.ToInt32(embeddedEvolutionPeriodArray[1].Substring(0, 2)), ToTime = embeddedEvolutionPeriodArray[1].Substring(2, 2) + ":00 UTC", }; evolution.Evolutions.Add(embeddedEvolution); // recurse on the remaining chunk to extract the weather elements it contains chunk = ParseEntitiesChunk(evolution, remaining, decodedTaf); } return(string.Empty); }
protected void SetPower(Powers powerName) { GetComponent <Player>().activeEvolutions++; evolution = GameManager.EvolutionManager.GetEvolutionByPowerName(powerName, true); if ((int)evolution.BodyPart < transform.GetChild((int)PlayerChildren.SlimeMesh).childCount) { affectedPart = transform.GetChild((int)PlayerChildren.SlimeMesh).GetChild((int)evolution.BodyPart).gameObject; } if (evolution.BodyPart == BodyPart.Hammer) { affectedPart.transform.SetParent(transform.GetChild((int)PlayerChildren.SlimeMesh).GetChild(0).GetChild(0).GetChild(0)); } else if (evolution.BodyPart == BodyPart.Staff) { affectedPart.transform.SetParent(transform.GetChild((int)PlayerChildren.SlimeMesh).GetChild(0).GetChild(0).GetChild(1)); } else if (evolution.BodyPart == BodyPart.Ghost) { //Change player appearence ((EvolutionGhost)(this)).SetGhostVisual(); //Then do Nothing affectedPart = transform.gameObject; } affectedPart.SetActive(true); Timer = evolution.duration; playerController = GetComponent <PlayerController>(); }
private static void UpdatePokemon() { var newEvolution = new Evolution(evolutionByType, evolutionByPower); var currentPokemon = pokemons.Where(p => p.Name == pokemonByName).FirstOrDefault(); currentPokemon.Evolutions.Add(newEvolution); }
/// <summary> /// Changes characteristics about the character based on what they're /// evolving into. /// </summary> /// <param name="evolutionType"></param> public void Evolve(EvolutionType evolutionType) { Evolution evolution = ReferenceManager.Instance.evolutionLibrary .GetComponent <EvolutionLibrary>().GetEvolution(evolutionType); SetCameraPosition(evolution.cameraZ); col.radius = evolution.colliderRadius; rend.sprite = evolution.sprite; rb.mass = evolution.mass; character.healthProperties.health = Mathf.RoundToInt( evolution.CalculateMaximumHealth() * Difficulty.Instance.GetHealthMult(gameObject) ); character.movementProperties.speed = Mathf.RoundToInt( evolution.CalculateMaximumSpeed() * Difficulty.Instance.GetSpeedMult(gameObject) ); foreach (Transform child in transform) { child.localScale = transform.localScale * evolution.CalculateStatMul(); } character.evolutionProperties.CurrentEvolution = evolution; }
override public void Add(uint amount_) { if (amount_ == 0) { return; } var evolution = new Evolution() { Previous = amount, Added = amount_ }; amount += amount_; if (maxAmount() > 0 && amount > maxAmount()) { evolution.Removed = amount - maxAmount(); amount = maxAmount(); } evolution.Current = amount; if (evolution.Previous == 0) { expiration = scheduler.Now + duration(); scheduler.Start(Update, ref coroutine); } _Changed(evolution); }
override public void Remove(uint amount_) { if (amount_ == 0) { return; } var evolution = new Evolution() { Previous = amount }; if (amount_ >= amount) { evolution.Removed = amount; amount = 0; expiration = 0; scheduler.Stop(ref coroutine); } else { evolution.Removed = amount_; amount -= amount_; } evolution.Current = amount; _Changed(evolution); }
// Use this for initialization void Start() { evolution = GameObject.Find("Evolution").GetComponent <Evolution>(); ErrorMessageColor = BCErrorMessage.color; savedLabelColor = SavedLabel.color; showOneAtATimeToggle.isOn = evolution.Settings.showOneAtATime; showOneAtATimeToggle.onValueChanged.AddListener(delegate(bool arg0) { evolution.Settings.showOneAtATime = arg0; evolution.RefreshVisibleCreatures(); }); showMuscleContractionToggle.isOn = PlayerPrefs.GetInt(PlayerPrefsKeys.SHOW_MUSCLE_CONTRACTION, 0) == 1; showMuscleContractionToggle.onValueChanged.AddListener(delegate(bool arg0) { PlayerPrefs.SetInt(PlayerPrefsKeys.SHOW_MUSCLE_CONTRACTION, arg0 ? 1 : 0); PlayerPrefs.Save(); evolution.RefreshVisibleCreatures(); bcController.RefreshMuscleContractionVisibility(); }); timeScaleSlider.onValueChanged.AddListener(delegate(float arg0) { evolution.TimeScale = arg0; timeScaleLabel.text = arg0.ToString("0.0") + "X"; }); }
// private Bitmap GetSourceBitmap() // { // Bitmap bitmap = (Bitmap) picPattern.Image; // return bitmap.Clone(new Rectangle(new Point(0,0), bitmap.Size), PixelFormat.Format32bppArgb); // } private void StartEvolution() { Evolution evolution = new Evolution((Bitmap)picPattern.Image); evolution.ReachedSignificantChange += evolution_ReachedSignificantChange; evolution.StartEvolution(); }
private void evolution_ReachedSignificantChange(Evolution evolution) { if (InvokeRequired) { Evolution.ReachedSignificantChangeEvent d = evolution_ReachedSignificantChange; Invoke(d, evolution); return; } lock (currentCandidate) { currentCandidate = evolution.CurrentCandidate; pnlCanvas.Invalidate(); } //SaveImageToFile(currentCandidate.Drawing); //SaveDrawingToFile(currentCandidate.Drawing) // TimeSpan totalTime = DateTime.Now - startTime; // double generationsPerSec = generation/totalTime.TotalSeconds; // int polygons = current.Drawing.Polygons.Count; // int points = current.Drawing.PointCount; // double pointsPerPolygon = 0; // if (polygons != 0) // pointsPerPolygon = (double)points / polygons; // // // Trace.WriteLine(string.Format( // "{0:yyyy-MM-dd HH:mm:ss} {1,15} {2,15} {3,9:0.0} {4,9} {5,9} {6,9:0.0}", // DateTime.Now, currentCandidate .ErrorLevel, generation, generationsPerSec, points, polygons, pointsPerPolygon)); }
// Use this for initialization void Start() { S = this; if (!start) { return; } if (history.hasToBeInitialised) { history.Clear(); for (int i = 0; i < keepTop; i++) { history.bestGenomes.Add(Genome.CreateRandom(genomeLength, geneLength)); } history.hasToBeInitialised = false; } environments.Clear(); history.CalculateMinMaxScore(); StartCoroutine(Simulation()); }
public void ShouldRunGenerationWithGradientMutators() { List <Position> positions = new List <Position>(); positions.Add(new Position(0, 0)); positions.Add(new Position(1, 1)); positions.Add(new Position(2, 2)); Population population = new Population(100, positions.Count); List <IGenomeFactory <int, int> > operators = new List <IGenomeFactory <int, int> >(); Evaluator evaluator = new Evaluator(positions); for (int k = 0; k < 50; k++) { operators.Add(new GradientMutator(evaluator)); } Evolution evolution = new Evolution(evaluator, operators); Population newpopulation = (Population)evolution.RunGeneration(population); Assert.IsNotNull(newpopulation); Assert.AreEqual(100, newpopulation.Genomes.Count); }
public override int GetHashCode() { int hash = 1; if (Evolution != 0) { hash ^= Evolution.GetHashCode(); } if (EvolutionItemRequirement != 0) { hash ^= EvolutionItemRequirement.GetHashCode(); } if (CandyCost != 0) { hash ^= CandyCost.GetHashCode(); } if (KmBuddyDistanceRequirement != 0F) { hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(KmBuddyDistanceRequirement); } if (Form != 0) { hash ^= Form.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
override public void Add(uint amount_) { if (amount_ == 0) { return; } var evolution = new Evolution() { Previous = Amount(), Added = amount_ }; amount += amount_; if (maxAmount() > 0 && Amount() > maxAmount()) { evolution.Removed = Amount() - maxAmount(); amount = maxAmount(); expiration = scheduler.Now + duration() * Amount(); scheduler.Start(Update, ref coroutine); } evolution.Current = Amount(); if (evolution.Previous == 0 || evolution.Removed > 0) { expiration = scheduler.Now + duration() * Amount(); scheduler.Start(Update, ref coroutine); } else { expiration += duration() * (evolution.Added - evolution.Removed); } _Changed(evolution); }
private static void AddNewPokemon() { var newEvolution = new Evolution(evolutionByType, evolutionByPower); var newPokemon = new Pokemon(pokemonByName, newEvolution); pokemons.Add(newPokemon); }
/// <summary> /// Method to continue on another users saved progress of their evolution /// </summary> /// <param name="filesLocation">Path to the files of the evolution a user wants to branch from</param> public ActionResult Continue(string filesLocation, string oldUsername, string sequence) { // get username string username = HttpContext.Session["userId"].ToString(); // set sequence if it existed if (sequence == null) { HttpContext.Session.Add("sequence", ""); } // set previous username for branching HttpContext.Session.Add("branchId", oldUsername); // create clean user folder in Results FileUtility.CreateUserFolder(username); // move files to username folder in Results FileUtility.CopyFilesToUserFolder(filesLocation, username, oldUsername); // Get client pool used for running the evaluations MalmoClientPool clientPool = Global.GloabalVariables.MalmoClientPool; //recreate experiment and load poppulation MinecraftBuilderExperiment experiment = new MinecraftBuilderExperiment(clientPool, "Simple", username); XmlDocument xmlConfig = new XmlDocument(); xmlConfig.Load(System.AppDomain.CurrentDomain.BaseDirectory + "minecraft.config.xml"); experiment.Initialize("Minecraft", xmlConfig.DocumentElement); // read current population var reader = XmlReader.Create(FileUtility.GetUserResultPath(username) + "Population.xml"); var list = experiment.LoadPopulation(reader); reader.Close(); //load video files List <Evolution> evolutions = new List <Evolution>(); for (int i = 0; i < list.Count; i++) { string folderName = i.ToString(); string videoPath = ""; videoPath = FileUtility.GetVideoPathWithoutDecoding(username, i.ToString()); //TODO: Change branch ID to 0 Evolution evolution = new Evolution() { ID = i, DirectoryPath = FileUtility.GetUserResultVideoPath(username, folderName), BranchID = i, Username = HttpContext.Session["userId"].ToString(), Sequence = sequence }; evolutions.Add(evolution); } if (sequence == null) { return(View("FirstEvolution", evolutions)); } return(View("Evolve", evolutions)); }
public void AddEvolution(Evolution evolution) { player.AddEvolution(evolution); foodRequirement += foodRequirementIncrement; startingTime += timeIncrement; StartGathering(); }
public EDSCategory(Evolution.Source source, Evolution.Cal taskList) { this.name = source.Name; this.uid = source.Uid; this.taskList = taskList; //Based on evolution/calendar/gui/e-cal-popup.c : //e_cal_popup_target_new_source this.isSystem = (string.Compare (source.RelativeUri, "system") == 0); }
static void Main(string[] args) { //fetch the dependencies - here we just create them var neighbourCalculator = new NeighbourCalculator(); var gameRules = new GameRules(new LiveCellRule(), new DeadCellRule()); var evolution = new Evolution(neighbourCalculator, gameRules); var gridRowColumnParser = new GridRowColumnParser(); //typically we would create such an object and inject its dependencies //using an IoC container IGameOfLife gameOfLife = new GameOfLifeUI.GameOfLife(evolution, gridRowColumnParser); gameOfLife.Start(); }
public EnemyLifeForm(EvolutionStage attackBehaviourStage, EvolutionStage defenseBehaviourStage, EvolutionStage movementBehaviourStage) { Evolution = new Evolution() { AttackBehaviour = GetAAttackBehaviour(attackBehaviourStage), DefenseBehaviour = GetDefenseBehaviour(defenseBehaviourStage), MovementBehaviour = GetMovementBehaviour(movementBehaviourStage) }; _defenseEvolutionStage = EvolutionStage.Default; _attackEvolutionStage = EvolutionStage.Default; _movementEvolutionStage = EvolutionStage.Default; }
public PlayerLifeForm() { Evolution = new Evolution() { AttackBehaviour = new DefaultAttackBehaviour(), DefenseBehaviour = new DefaultDefenseBehaviour(), MovementBehaviour = new DefaultMovementBehaviour(), }; _defenseEvolutionStage = EvolutionStage.Default; _attackEvolutionStage = EvolutionStage.Default; _movementEvolutionStage = EvolutionStage.Default; Rotation = MathHelper.ToRadians(0); }
static void Main(string[] args) { int numOrgs = 64; string[] orgs = new string[numOrgs]; Evolution ev = new Evolution(); for (int i = 0; i < numOrgs; i++) { orgs[i] = ev.Init(); Console.WriteLine(orgs[i]); } ev.Tournament(numOrgs, orgs); Console.ReadKey(); }
public void SolveTravelingSalesmanProblem() { var citiesCoordinates = new List<TravelingSalesmanCity>() { new TravelingSalesmanCity('A', 0, 0), new TravelingSalesmanCity('B', 10, 100), new TravelingSalesmanCity('C', 20, 20), new TravelingSalesmanCity('D', 60, 20), new TravelingSalesmanCity('E', 30, 10), new TravelingSalesmanCity('F', 50, 70), new TravelingSalesmanCity('G', 70, 30), new TravelingSalesmanCity('H', 30, 30), new TravelingSalesmanCity('I', 50, 80) }; var random = new RandomNumberGenerators.Default(); var genePool = new Chromosomes.GenePool<char>(); genePool.AddRange(new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' }); var chromosomeFactory = new Chromosomes.PermutationChromosomeFactory<int>(random, genePool, 9); // chromosome as a permutation of 1-9 numbers var fitnessCalc = new TravelingSalesmanProblemFitnessCalculator(citiesCoordinates); var mutationStrategy = new MutationStrategies.SingleGeneMutation(random, 0.02); // mutation rate fixed to 2% var crossoverStrategy = new CrossoverStrategies.DoubleCut(random); var selectionStrategy = new SelectionStrategies.RouletteWheel(random); var migrationStrategy = new MigrationStrategies.Random(random, 0.05); // random migration with chance of occurence 5% var populationStrategy = new PopulationStrategies.MultiPopulation(10, 50, migrationStrategy); // 10 population with fixed size of 50 // need to pass something telling that fitness is a total distance so the shortest the better var evolution = new Evolution(random, chromosomeFactory, populationStrategy, mutationStrategy, crossoverStrategy, selectionStrategy); do { evolution.Step(); if (evolution.TopFitness == 1.0) { return; } } while (evolution.Generation < 1000); Assert.Fail(); }
public MainContext(Evolution evolution) : base(evolution) { NewCommand = CommandFactory.Create(New); OpenCommand = CommandFactory.Create<FilePathProvider>(Open); SaveAsCommand = CommandFactory.Create<FilePathProvider>(SaveAs); SaveCommand = CommandFactory.Create(Save, CanSave, this, FilePathProperty); RemoveFighterCommand = CommandFactory.Create(RemoveFighter, IsFighterSelected, this, SelectedFighterProperty); MoveFighterUpCommand = CommandFactory.Create(MoveSelectedFighterUp, IsFighterSelected, this, SelectedFighterProperty); MoveFighterDownCommand = CommandFactory.Create(MoveSelectedFighterDown, IsFighterSelected, this, SelectedFighterProperty); New(); }
public UndoableContext(Evolution evolution) { _evolution = evolution; if (_evolution != null) { UndoCommand = CommandFactory.Create( evolution.Undo, () => evolution.CanUndo, evolution, Evolution.CanUndoProperty); RedoCommand = CommandFactory.Create( evolution.Redo, () => evolution.CanRedo, evolution, Evolution.CanRedoProperty); } }
private void OnContactsAdded(object o, Evolution.ContactsAddedArgs args) { Console.WriteLine ("Contacts added:"); foreach (Evolution.Contact contact in args.Contacts) { Console.WriteLine ("\nId: {0}", contact.Id); Console.WriteLine ("Fullname: {0}", contact.FullName); } }
public void TasksAdded(object o, Evolution.ObjectsAddedArgs args) { Logger.Debug ("Tasks Added "); CalComponent[] addedTasks = CalUtil.ICalToCalComponentArray (args.Objects.Handle, ((CalView) o).Client); lock (taskLock) { Gtk.TreeIter taskIter; EDSTask edsTask; EDSCategory edsCategory; foreach (CalComponent task in addedTasks) { if(!taskIters.ContainsKey(task.Uid)) { edsCategory = new EDSCategory (task.Source); edsTask = new EDSTask (task, edsCategory); taskIter = taskStore.AppendNode (); taskStore.SetValue (taskIter, 0, edsTask); taskIters [edsTask.Id] = taskIter; } } } }
public void TasksModified(object o, Evolution.ObjectsModifiedArgs args) { Logger.Debug ("Tasks Modified "); Gtk.TreeIter iter; EDSTask edsTask; EDSCategory edsCategory; CalComponent[] modifiedTasks = CalUtil.ICalToCalComponentArray (args.Objects.Handle, ((CalView) o).Client); foreach (CalComponent task in modifiedTasks) { Logger.Debug ("Modified : " + task.Summary); if(taskIters.ContainsKey(task.Uid)) { edsCategory = new EDSCategory (task.Source); edsTask = new EDSTask (task, edsCategory); iter = taskIters[edsTask.Id]; taskStore.SetValue (iter, 0, edsTask); } } }
public void TasksRemoved(object o, Evolution.ObjectsRemovedArgs args) { Logger.Debug ("Tasks Removed"); Gtk.TreeIter iter; GLib.List removedTasksList = new GLib.List (args.Uids.Handle, typeof (CalComponentId)); foreach (CalComponentId id in removedTasksList) { if(taskIters.ContainsKey(id.Uid)) { iter = taskIters[id.Uid]; taskStore.Remove (ref iter); } } Logger.Debug ("{0} Tasks removed in EDS", removedTasksList.Count); }
private void AddCategory(Evolution.Source source) { Logger.Debug ("AddCategory"); EDSCategory edsCategory; Gtk.TreeIter iter; if (source.IsLocal()) { Cal taskList = new Cal (source, CalSourceType.Todo); edsCategory = new EDSCategory (source, taskList); iter = categoryListStore.Append (); categoryListStore.SetValue (iter, 0, edsCategory); //Assumption : EDS Creates atleast one System category. if (edsCategory.IsSystem) this.defaultCategory = edsCategory; if (!taskList.Open (true)) { Logger.Debug ("laskList Open failed"); return; } CalView query = taskList.GetCalView ("#t"); if (query == null) { Logger.Debug ("Query object creation failed"); return; } else query.Start (); query.ObjectsModified += TasksModified; query.ObjectsAdded += TasksAdded; query.ObjectsRemoved += TasksRemoved; } }
private void Init() { mGestation = 0; mCurrentState = Evolution.Seed; //IPickable.mIsPickable = false; //IPickable.mIsFragile = true; }
public static IActivationFunction GetRandomActivationFunction(Evolution.NeatParameters np) { return functions[Maths.RouletteWheel.SingleThrow(np.activationProbabilities)]; }
public FileViewerMediaType GetMediaType(Evolution.Extensibility.Storage.Version1.ICentralizedFile file, IFileViewerOptions options) { throw new FileViewerNotSupportedException(); }
public string Render(Evolution.Extensibility.Storage.Version1.ICentralizedFile file, IFileViewerOptions options) { throw new FileViewerNotSupportedException(); }
public OuterTransactionScope(Evolution evolution) { _evolution = evolution; }
public Container (Evolution.Source source, EvolutionDataServerQueryable queryable, string fingerprint) { this.source = source; this.queryable = queryable; this.fingerprint = fingerprint; }
public abstract void PokedexInsertEvolution(Evolution f);
private void OnContactsChanged(object o, Evolution.ContactsChangedArgs args) { }
private void OnContactsRemoved(object o, Evolution.ContactsRemovedArgs args) { }
public void Find_the_first_chromoSome_that_solves_the_puzzle() { Stopwatch watch = new Stopwatch(); watch.Start(); float target = 63F; int populationSize = 1000; var population = Population.NewPopulation(target, populationSize, new Random()); var evolution = new Evolution(target, population); var solution = evolution.FindSolution(.7, .001, 1000); watch.Stop(); Console.WriteLine("Ms to solution: {0}", watch.ElapsedMilliseconds); Console.WriteLine("Number of generations: {0}", solution.GenCount); Console.WriteLine("Fitness: {0}, Solution: {1}, Answer: {2}", solution.Fitness, population.Decode(solution.Bits), solution.Answer); Console.WriteLine("Bits: {0}", solution.Bits); Assert.Equal(target, solution.Answer); foreach (var c in solution.Population.All()) { Console.WriteLine("Current generations solutions"); Console.WriteLine("Fitness: {0}, Solution: {1}, Answer: {2}", c.Fitness, population.Decode(c.Bits), c.Answer); } }
protected void OnBtnStartClicked(object sender, EventArgs e) { btn_Start.Sensitive = false; txt_Output.Buffer.Clear(); try { Problem problem = null; switch (cbo_Problem.Active) { case 0 : problem = new TravelingSalesMan(); break; case 1 : problem = new Griewank(); break; case 2 : problem = new Ackley(); break; case 3 : problem = new Nullstelle(); break; } if (problem == null) throw new NullReferenceException(); problem.countGene = (int)txt_countGenes.Value; problem.maxGenerations = (int)txt_maxGeneration.Value; problem.countIndividuals = (int)txt_countIndividuals.Value; problem.countChilds = (int)txt_countChilds.Value; problem.recombinationProbability = txt_recombProb.Value; if (cbo_Encryption.Active == 1) { problem.RecombBinaryIsSinglePoint = (cbo_recombBinary.Active == 0)? true : (cbo_recombBinary.Active == 1)? false : (bool?)null; } if (cbo_Encryption.Active == 2) { problem.RecombRealIsIntermidiate = cbo_recombReal.Active == 0; } problem.InvertOnMutate = rb_Invert.Active ? true : false; problem.minAllelValue = problem.minAllelValue == 0 ? 1 : problem.minAllelValue; problem.maxAllelValue = problem.maxAllelValue == 0 ? problem.countGene + 1 : problem.maxAllelValue; problem.SelPropType = rb_Fitness.Active ? main.Helper.Enums.SelPropType.Fitness : main.Helper.Enums.SelPropType.Ranking; problem.SelType = (main.Helper.Enums.SelType)cbo_SelType.Active; problem.Encryption = (main.Helper.Enums.Encryption)cbo_Encryption.Active; problem.TournamentMemberCount = (int)txt_TournamentMemberCount.Value; Evolution evol = new Evolution(problem); //Methode zum behandeln des Fortschritt-Events zuweisen evol.OnProgress += new Evolution.OnProgressEvent(OnEvolutionProgressChanged); // Laufzeitmessung watch.Start(); evol.Compute(); //Laufzeitauswertung watch.Reset(); txt_Output.Buffer.Text = problem.Output.ToString(); btn_Start.Sensitive = true; } catch (Exception ex) { txt_Output.Buffer.Text += "\r\n\r\nFehler: " + ex.Message + "\r\n\r\n" + ex.StackTrace; btn_Start.Sensitive = true; } }