private void createNodesConnetions(List <Row> rows) { for (int i = 1; i < rows.Count - 1; ++i) { var row = rows[i]; Row nextRow = getNextRow(rows, i); Row previousRouw = getPreviousRow(rows, i); if (i == 1) { previousRouw = null; } if (i == rows.Count - 2) { nextRow = null; } List <Row> longRows = createLongRowList(rows, i); tryToConnectNode(row, nextRow, previousRouw, longRows); } if (NoRandoms == false) { for (int i = 0; i < (rows.Count - 2) * 2;) //dodanie 2N krawedzi w sposob losowy { var weight = rand.Next(1, 11); var startRow = rows.SelectRandom(1, rows.Count - 1); var node1 = startRow.SelectRandom(); var endRow = rows.SelectRandom(1, rows.Count - 1); var node2 = endRow.SelectRandom(); if (node1.Index == node2.Index) { continue; } if (node1.JoinedTo.FirstOrDefault(n => n == node2) != null) { continue; } connectNodes(node1, node2, weight); ++i; } } var startNode = rows[0][0]; foreach (var node in rows[1]) { connectNodes(startNode, node, rand.Next(1, 11)); } var endNode = rows[rows.Count - 1][0]; foreach (var node in rows[rows.Count - 2]) { connectNodes(node, endNode, rand.Next(1, 11)); } }
void ReanimateCultist() { if (summons.Empty()) { return; } List <Creature> temp = new List <Creature>(); foreach (var guid in summons.ToList()) { Creature cre = ObjectAccessor.GetCreature(me, guid); if (cre) { if (cre.IsAlive() && (cre.GetEntry() == CreatureIds.CultFanatic || cre.GetEntry() == CreatureIds.CultAdherent)) { temp.Add(cre); } } } if (temp.Empty()) { return; } Creature cultist = temp.SelectRandom(); DoCast(cultist, LadySpells.DARK_MARTYRDOM_T, true); }
/// <summary> /// Select the best target (in <targetType> order) satisfying <predicate> from the threat list. /// If <offset> is nonzero, the first <offset> entries in <targetType> order (or MAXTHREAT order, if <targetType> is RANDOM) are skipped. /// </summary> public Unit SelectTarget(SelectAggroTarget targetType, uint offset, ISelector selector) { ThreatManager mgr = GetThreatManager(); // shortcut: if we ignore the first <offset> elements, and there are at most <offset> elements, then we ignore ALL elements if (mgr.GetThreatListSize() <= offset) { return(null); } List <Unit> targetList = SelectTargetList((uint)mgr.GetThreatListSize(), targetType, offset, selector); // maybe nothing fulfills the predicate if (targetList.Empty()) { return(null); } switch (targetType) { case SelectAggroTarget.MaxThreat: case SelectAggroTarget.MinThreat: case SelectAggroTarget.MaxDistance: case SelectAggroTarget.MinDistance: return(targetList[0]); case SelectAggroTarget.Random: return(targetList.SelectRandom()); default: return(null); } }
public void ReplaceRandomBranch(IRandom random, ISymbolicExpressionTree symbolicExpressionTree, int maxTreeLength, int maxTreeDepth) { var allowedSymbols = new List <ISymbol>(); ISymbolicExpressionTreeNode parent; int childIndex; int maxLength; int maxDepth; // repeat until a fitting parent and child are found (MAX_TRIES times) int tries = 0; do { #pragma warning disable 612, 618 parent = symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1).Where(n => n.SubtreeCount > 0).SelectRandom(random); #pragma warning restore 612, 618 childIndex = random.Next(parent.SubtreeCount); var child = parent.GetSubtree(childIndex); maxLength = maxTreeLength - symbolicExpressionTree.Length + child.GetLength(); maxDepth = maxTreeDepth - symbolicExpressionTree.Root.GetBranchLevel(child); allowedSymbols.Clear(); foreach (var symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)) { // check basic properties that the new symbol must have if ((symbol.Name != child.Symbol.Name || symbol.MinimumArity > 0) && symbol.InitialFrequency > 0 && parent.Grammar.GetMinimumExpressionDepth(symbol) <= maxDepth && parent.Grammar.GetMinimumExpressionLength(symbol) <= maxLength) { allowedSymbols.Add(symbol); } } tries++; } while (tries < MAX_TRIES && allowedSymbols.Count == 0); if (tries < MAX_TRIES) { var weights = allowedSymbols.Select(s => s.InitialFrequency).ToList(); #pragma warning disable 612, 618 var seedSymbol = allowedSymbols.SelectRandom(weights, random); #pragma warning restore 612, 618 // replace the old node with the new node var seedNode = seedSymbol.CreateTreeNode(); if (seedNode.HasLocalParameters) { seedNode.ResetLocalParameters(random); } CutPointSymbolParameter.ActualValue = (ISymbol)parent.Symbol.Clone(); RemovedBranchParameter.ActualValue = new SymbolicExpressionTree((ISymbolicExpressionTreeNode)parent.GetSubtree(childIndex).Clone()); parent.RemoveSubtree(childIndex); parent.InsertSubtree(childIndex, seedNode); ProbabilisticTreeCreator.PTC2(random, seedNode, maxLength, maxDepth); AddedBranchParameter.ActualValue = new SymbolicExpressionTree((ISymbolicExpressionTreeNode)parent.GetSubtree(childIndex).Clone()); } }
void FilterTargets(List <WorldObject> targets) { if (GetCaster().ToPlayer().GetGroup() == null) { targets.Clear(); targets.Add(GetCaster()); } else { targets.Remove(GetExplTargetUnit()); List <Unit> tempTargets = new List <Unit>(); foreach (var obj in targets) { if (obj.IsTypeId(TypeId.Player) && GetCaster().IsInRaidWith(obj.ToUnit())) { tempTargets.Add(obj.ToUnit()); } } if (tempTargets.Empty()) { targets.Clear(); FinishCast(SpellCastResult.DontReport); return; } Unit target = tempTargets.SelectRandom(); targets.Clear(); targets.Add(target); } }
private void tryToConnectNode(Row row, Row nextRow, Row previousRow, List <Row> longRows) { foreach (var node in row) { while (nextRow != null && Utils.CheckChance(NodeNeighbourJoinPropability)) { ConnectNodeToRandomRowNode(node, nextRow); } while (longRows.Count > 0 && Utils.CheckChance(NodeLongDistanceJoinProability)) { ConnectNodeToRandomRowNode(node, longRows.SelectRandom()); } while (node.JoinedTo.Count == 0 && nextRow != null) { ConnectNodeToRandomRowNode(node, nextRow); } while (node.JoinedFrom.Count == 0 && previousRow != null) { ConnectRandomRowNodeToNode(previousRow, node); } } }
public TournamentRound GetRandomRound(TournamentRound vanilla, TournamentGame.QualificationMode qualificationMode) { var matches = new List <TournamentRound>(); if (Enable1Match2Teams) { matches.Add(new (ParticipantCount, 1, 2, WinnerCount, qualificationMode)); } if (Enable1Match4Teams) { matches.Add(new (ParticipantCount, 1, 4, WinnerCount, qualificationMode)); } if (Enable2Match2Teams) { matches.Add(new (ParticipantCount, 2, 2, WinnerCount, qualificationMode)); } if (Enable2Match4Teams) { matches.Add(new (ParticipantCount, 2, 4, WinnerCount, qualificationMode)); } if (Enable4Match2Teams) { matches.Add(new (ParticipantCount, 4, 2, WinnerCount, qualificationMode)); } if (EnableVanilla || !matches.Any()) { matches.Add(vanilla); } return(matches.SelectRandom()); }
void OnTargetSelect(List <WorldObject> targets) { // Find the best target - prefer players over pets bool foundPlayer = false; foreach (WorldObject worldObject in targets) { if (worldObject.IsPlayer()) { foundPlayer = true; break; } } if (foundPlayer) { targets.RemoveAll(new ObjectTypeIdCheck(TypeId.Player, false)); } // choose one random target from targets if (targets.Count > 1) { WorldObject selected = targets.SelectRandom(); targets.Clear(); targets.Add(selected); } }
void EmpowerCultist() { if (summons.Empty()) { return; } List <Creature> temp = new List <Creature>(); foreach (var guid in summons) { Creature cre = ObjectAccessor.GetCreature(me, guid); if (cre) { if (cre.IsAlive() && (cre.GetEntry() == CreatureIds.CultFanatic || cre.GetEntry() == CreatureIds.CultAdherent)) { temp.Add(cre); } } } // noone to empower if (temp.Empty()) { return; } // select random cultist Creature cultist = temp.SelectRandom(); DoCast(cultist, cultist.GetEntry() == CreatureIds.CultFanatic ? LadySpells.DARK_TRANSFORMATION_T : LadySpells.DARK_EMPOWERMENT_T, true); Talk(cultist.GetEntry() == CreatureIds.CultFanatic ? LadyTexts.SAY_DARK_TRANSFORMATION : LadyTexts.SAY_DARK_EMPOWERMENT); }
public void TestRandom() { var TestList = new List <int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var random = TestList.SelectRandom(); Assert.NotNull(random); }
void HandleTargetSelect(List <WorldObject> targets) { // choose one random target from targets if (targets.Count > 1) { WorldObject selected = targets.SelectRandom(); targets.Clear(); targets.Add(selected); } }
public void TestSelectRandom() { var test = new List <int>() { 25, 67, 10, 88, 35124, 6524, 5, 125, 654, 56, 1, 5451, 15211, 22101, 65121, 1254, 15121, 210, 310, 510, 610, 710, 810, 910 }; var r = test.SelectRandom(); var rInList = test.Contains(r); Assert.IsTrue(rInList); }
void FilterTargets(List <WorldObject> targets) { if (targets.Empty()) { return; } WorldObject target = targets.SelectRandom(); targets.Clear(); targets.Add(target); }
public override ObjectGuid GetGuidData(uint type) { switch (type) { case DataTypes.ElderNadox: return(ElderNadoxGUID); case DataTypes.PrinceTaldaram: return(PrinceTaldaramGUID); case DataTypes.JedogaShadowseeker: return(JedogaShadowseekerGUID); case DataTypes.Amanitar: return(AmanitarGUID); case DataTypes.HeraldVolazj: return(HeraldVolazjGUID); case DataTypes.PrinceTaldaramPlatform: return(PrinceTaldaramPlatformGUID); case DataTypes.AddJedogaInitiand: { List <ObjectGuid> vInitiands = new List <ObjectGuid>(); foreach (ObjectGuid guid in InitiandGUIDs) { Creature cr = instance.GetCreature(guid); if (cr && cr.IsAlive()) { vInitiands.Add(guid); } } if (vInitiands.Empty()) { return(ObjectGuid.Empty); } return(vInitiands.SelectRandom()); } case DataTypes.AddJedogaVictim: return(JedogaSacrifices); case DataTypes.PlJedogaTarget: return(JedogaTarget); default: break; } return(ObjectGuid.Empty); }
public override string Scramble() { if (scramblers == null) { MessageBox.Show("No file selected.", "error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(null); } var total = scramblers.Sum(x => x.Weight); var scrambler = scramblers.SelectRandom(x => new Fraction(x.Weight, total), rand); return(scrambler.Scramble(rand)); }
public List <Hunter> SpawnRandom(int amount, HunterStats stats, List <Hunter> parents = null) { List <Hunter> spawned = new List <Hunter>(); for (int i = 0; i < amount; i++) { Transform spawnPoint = SpawnPoints.SelectRandom(); Vector3 pos = spawnPoint.position.WithinRandomRadius(SpawnPointRadius); spawned.Add(SpawnHunter(stats, pos, parents)); } return(spawned); }
IEnumerator SpawnFood() { while (DoResourcesRespawn) { if (currentFoodAmount < MaxResourceAbundance) { Transform spawnPoint = FoodSpawnPoints.SelectRandom(); Vector3 pos = spawnPoint.position.WithinRandomRadius(FoodSpawnPointRadius); MakeFood(pos); currentFoodAmount += 1; } yield return(new WaitForSeconds(ResourceRespawnInterval)); } }
void FilterTargets(List <WorldObject> targets) { // get a list of players with mana targets.RemoveAll(unit => unit.IsTypeId(TypeId.Player) && unit.ToPlayer().GetPowerType() == PowerType.Mana); if (targets.Empty()) { return; } WorldObject target = targets.SelectRandom(); targets.Clear(); targets.Add(target); }
private void seedCenters() { UpdateManager.WriteLine("Performing K-Means++ initialization..."); LabelVector center = _data.SelectRandom().Clone() as LabelVector; center.Label = 0; _centers.Add(center); Stopwatch sw = new Stopwatch(); for (int i = 1; i < _k; i++) { sw.Reset(); UpdateManager.Write("Recalculating phi..."); sw.Start(); runJobs(o => calculatePhi(o)); sw.Stop(); UpdateManager.WriteLine("Done [{0}ms]", sw.ElapsedMilliseconds); float[] dist = _data.Select(o => o.FeatureValue).ToArray().Normalize(); LabelVector x = _data[dist.Sample()]; _centers.Add(x.Clone() as LabelVector); } }
public void Restart(int triangleIndex = -1) { Debug.Log("Restarting"); StopAllCoroutines(); if (Dirty) { CleanUp(); } meshFilter.mesh.Clear(); iterator.CreateIteration(triangleIndex == -1 ? MeshFaces.SelectRandom() : MeshFaces[triangleIndex]); iterator.StartIterating(); Dirty = true; }
public override void IsSummonedBy(Unit summoner) { if (summoner.GetEntry() == CreatureIds.Midnight) { _phase = Phases.AttumenEngages; } if (summoner.GetEntry() == CreatureIds.AttumenUnmounted) { _phase = Phases.Mounted; DoCastSelf(SpellIds.SpawnSmoke); _scheduler.Schedule(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(25), task => { Unit target = null; var t_list = me.GetThreatManager().getThreatList(); List <Unit> target_list = new List <Unit>(); foreach (var itr in t_list) { target = Global.ObjAccessor.GetUnit(me, itr.getUnitGuid()); if (target && !target.IsWithinDist(me, 8.00f, false) && target.IsWithinDist(me, 25.0f, false)) { target_list.Add(target); } target = null; } if (!target_list.Empty()) { target = target_list.SelectRandom(); } DoCast(target, SpellIds.Charge); task.Repeat(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(25)); }); _scheduler.Schedule(TimeSpan.FromSeconds(25), TimeSpan.FromSeconds(35), task => { DoCastVictim(SpellIds.Knockdown); task.Repeat(TimeSpan.FromSeconds(25), TimeSpan.FromSeconds(35)); }); } }
// Select the targets satifying the predicate. // predicate shall extend std.unary_function<Unit*, bool> public List <Unit> SelectTargetList(ISelector selector, uint maxTargets, SelectAggroTarget targetType) { var targetList = new List <Unit>(); var threatlist = GetThreatManager().getThreatList(); if (threatlist.Empty()) { return(targetList); } foreach (var hostileRef in threatlist) { if (selector.Check(hostileRef.getTarget())) { targetList.Add(hostileRef.getTarget()); } } if (targetList.Count < maxTargets) { return(targetList); } if (targetType == SelectAggroTarget.Nearest || targetType == SelectAggroTarget.Farthest) { SortByDistanceTo(me, targetList); } if (targetType == SelectAggroTarget.Farthest || targetType == SelectAggroTarget.BottomAggro) { targetList.Reverse(); } if (targetType == SelectAggroTarget.Random) { targetList = targetList.SelectRandom(maxTargets).ToList(); } else { targetList.Resize(maxTargets); } return(targetList); }
public async override Task InitializeStore() { if (isInitialized) { return; } auctionItems = new List <AuctionItem>(); List <string> condition = new List <string> { "new", "used", "broken", "only driven once" }; List <string> imageUrls = new List <string> { "http://dumouchelle.com/lotImages/201606/1200/2016060001_1.jpg", "http://dumouchelle.com/lotImages/201606/1200/2016060001_2.jpg", "http://dumouchelle.com/lotImages/201606/1200/2016060001_3.jpg", }; // generate items for each auction foreach (var auction in await auctionStore.GetItemsAsync()) { var numItems = random.Next(100, 300); for (int i = 0; i < numItems; i++) { AuctionItem item = new AuctionItem(); item.Id = Guid.NewGuid().ToString(); item.LotNumber = i; item.LowerEstimate = random.Next(100, 10000); item.UpperEstimate = item.LowerEstimate * 1.5m; item.Description = "Some Description for item " + i; item.Details = "A bunch of details for item " + i; item.AuctionId = auction.Id; item.Condition = condition.SelectRandom(); item.Image = imageUrls.SelectRandom(); // add to mock collection auctionItems.Add(item); } } isInitialized = true; }
protected static ISymbolicExpressionTreeNode GenerateAndInsertNewSubtree(IRandom random, ISymbolicExpressionTreeNode parent, List <ISymbol> allowedSymbols, int childIndex, int maxLength, int maxDepth) { var weights = allowedSymbols.Select(s => s.InitialFrequency).ToList(); #pragma warning disable 612, 618 var seedSymbol = allowedSymbols.SelectRandom(weights, random); #pragma warning restore 612, 618 // replace the old node with the new node var seedNode = seedSymbol.CreateTreeNode(); if (seedNode.HasLocalParameters) { seedNode.ResetLocalParameters(random); } parent.RemoveSubtree(childIndex); parent.InsertSubtree(childIndex, seedNode); ProbabilisticTreeCreator.PTC2(random, seedNode, maxLength, maxDepth); return(seedNode); }
Player SelectTargetInDalaran() { List <Player> PlayerInDalaranList = new List <Player>(); var players = me.GetMap().GetPlayers(); foreach (var player in players) { if (player.GetZoneId() == me.GetZoneId() && !player.IsFlying() && !player.IsMounted() && !player.IsGameMaster()) { PlayerInDalaranList.Add(player); } } if (PlayerInDalaranList.Empty()) { return(null); } return(PlayerInDalaranList.SelectRandom()); }
void PlaceStarterProgressionItem(Random random) { var starterProgressionItems = new List <ItemInfo> { ItemInfoProvider.Get(EInventoryRelicType.Dash), ItemInfoProvider.Get(EInventoryRelicType.Dash), ItemInfoProvider.Get(EInventoryRelicType.DoubleJump), ItemInfoProvider.Get(EInventoryRelicType.DoubleJump), ItemInfoProvider.Get(EInventoryRelicType.TimespinnerWheel), ItemInfoProvider.Get(EInventoryRelicType.TimespinnerWheel), ItemInfoProvider.Get(EInventoryRelicType.PyramidsKey), }; if (!SeedOptions.ProgressiveVerticalMovement) { starterProgressionItems.Add(ItemInfoProvider.Get(EInventoryOrbType.Barrier, EOrbSlot.Spell)); starterProgressionItems.Add(ItemInfoProvider.Get(EInventoryRelicType.EssenceOfSpace)); } var starterProgressionItem = starterProgressionItems.SelectRandom(random); var shouldGiveLightwallAsSpell = ShouldGiveLightwall(random, starterProgressionItem); if (shouldGiveLightwallAsSpell) { GiveOrbsToMom(random, true); } else { GiveOrbsToMom(random, false); if (SeedOptions.StartWithTalaria) { return; } PutStarterProgressionItemInReachableLocation(random, starterProgressionItem); } }
void HandleTargets(List <WorldObject> targetList) { // Remove any Watchers that are already in combat for (var i = 0; i < targetList.Count; ++i) { Creature creature = targetList[i].ToCreature(); if (creature) { if (creature.IsAlive() && !creature.IsInCombat()) { continue; } } targetList.RemoveAt(i); } // Default to Krik'thir himself if he isn't engaged WorldObject target = null; if (GetCaster() && !GetCaster().IsInCombat()) { target = GetCaster(); } // Unless there are Watchers that aren't engaged yet if (!targetList.Empty()) { // If there are, pick one of them at random target = targetList.SelectRandom(); } // And hit only that one targetList.Clear(); if (target) { targetList.Add(target); } }
public async override Task InitializeStore() { if (initialized) { return; } auctions = new List <Auction>(); // some random data List <string> locations = new List <string> { "Melbourne", "Sydney", "New York", "London" }; for (int i = 0; i < 3; i++) { Auction auction = new Auction(); auction.AuctionDate = DateTime.Now.AddDays(i); auction.Location = locations.SelectRandom(); auctions.Add(auction); } initialized = true; }
public override void UpdateAI(uint diff) { if (!UpdateVictim()) { return; } _events.Update(diff); if (me.HasUnitState(UnitState.Casting)) { return; } _events.ExecuteEvents(eventId => { switch (eventId) { case EventIds.CloseDoor: GameObject door = instance.GetGameObject(ANDataTypes.AnubarakWall); if (door) { door.SetGoState(GameObjectState.Ready); } break; case EventIds.Pound: DoCastVictim(SpellIds.Pound); _events.Repeat(TimeSpan.FromSeconds(26), TimeSpan.FromSeconds(32)); break; case EventIds.LeechingSwarm: Talk(TextIds.SayLocust); DoCastAOE(SpellIds.LeechingSwarm); _events.Repeat(TimeSpan.FromSeconds(25), TimeSpan.FromSeconds(28)); break; case EventIds.CarrionBeetles: DoCastAOE(SpellIds.CarrionBeetles); _events.Repeat(TimeSpan.FromSeconds(24), TimeSpan.FromSeconds(27)); break; case EventIds.Impale: Creature impaleTarget = ObjectAccessor.GetCreature(me, _impaleTarget); if (impaleTarget) { DoCast(impaleTarget, SpellIds.ImpaleDamage, true); } break; case EventIds.Submerge: Talk(TextIds.SaySubmerge); DoCastSelf(SpellIds.Submerge); break; case EventIds.Darter: { List <Creature> triggers = new List <Creature>(); me.GetCreatureListWithEntryInGrid(triggers, CreatureIds.WorldTrigger); if (!triggers.Empty()) { var it = triggers.SelectRandom(); it.CastSpell(it, SpellIds.SummonDarter, true); _events.Repeat(TimeSpan.FromSeconds(11)); } else { EnterEvadeMode(EvadeReason.Other); } break; } case EventIds.Assassin: { Creature trigger = ObjectAccessor.GetCreature(me, _assassinTrigger); if (trigger) { trigger.CastSpell(trigger, SpellIds.SummonAssassin, true); trigger.CastSpell(trigger, SpellIds.SummonAssassin, true); if (_assassinCount > 2) { _assassinCount -= 2; _events.Repeat(TimeSpan.FromSeconds(20)); } else { _assassinCount = 0; } } else // something went wrong { EnterEvadeMode(EvadeReason.Other); } break; } case EventIds.Guardian: { Creature trigger = ObjectAccessor.GetCreature(me, _guardianTrigger); if (trigger) { trigger.CastSpell(trigger, SpellIds.SummonGuardian, true); trigger.CastSpell(trigger, SpellIds.SummonGuardian, true); if (_guardianCount > 2) { _guardianCount -= 2; _events.Repeat(TimeSpan.FromSeconds(20)); } else { _guardianCount = 0; } } else { EnterEvadeMode(EvadeReason.Other); } } break; case EventIds.Venomancer: { Creature trigger = ObjectAccessor.GetCreature(me, _guardianTrigger); if (trigger) { trigger.CastSpell(trigger, SpellIds.SummonVenomancer, true); trigger.CastSpell(trigger, SpellIds.SummonVenomancer, true); if (_venomancerCount > 2) { _venomancerCount -= 2; _events.Repeat(TimeSpan.FromSeconds(20)); } else { _venomancerCount = 0; } } else { EnterEvadeMode(EvadeReason.Other); } } break; default: break; } if (me.HasUnitState(UnitState.Casting)) { return; } }); DoMeleeAttackIfReady(); }
/// <summary> /// Takes two parent individuals P0 and P1. /// Randomly choose a node i from the first parent, then for each matching node j from the second parent, calculate the behavioral distance based on the range: /// d(i,j) = 0.5 * ( abs(max(i) - max(j)) + abs(min(i) - min(j)) ). /// Next, assign probabilities for the selection of a node j based on the inversed and normalized behavioral distance, then make a random weighted choice. /// </summary> public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, T problemData, IList <int> rows, int maxDepth, int maxLength) { var crossoverPoints0 = new List <CutPoint>(); parent0.Root.ForEachNodePostfix((n) => { // the if clauses prevent the root or the startnode from being selected, although the startnode can be the parent of the node being swapped. if (n.Parent != null && n.Parent != parent0.Root) { crossoverPoints0.Add(new CutPoint(n.Parent, n)); } }); var crossoverPoint0 = crossoverPoints0.SampleRandom(random); int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child); int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength(); var allowedBranches = new List <ISymbolicExpressionTreeNode>(); parent1.Root.ForEachNodePostfix((n) => { if (n.Parent != null && n.Parent != parent1.Root) { if (n.GetDepth() + level <= maxDepth && n.GetLength() + length <= maxLength && crossoverPoint0.IsMatchingPointType(n)) { allowedBranches.Add(n); } } }); if (allowedBranches.Count == 0) { return(parent0); } var dataset = problemData.Dataset; // create symbols in order to improvize an ad-hoc tree so that the child can be evaluated var rootSymbol = new ProgramRootSymbol(); var startSymbol = new StartSymbol(); var tree0 = CreateTreeFromNode(random, crossoverPoint0.Child, rootSymbol, startSymbol); // this will change crossoverPoint0.Child.Parent double min0 = 0.0, max0 = 0.0; foreach (double v in interpreter.GetSymbolicExpressionTreeValues(tree0, dataset, rows)) { if (min0 > v) { min0 = v; } if (max0 < v) { max0 = v; } } crossoverPoint0.Child.Parent = crossoverPoint0.Parent; // restore correct parent var weights = new List <double>(); foreach (var node in allowedBranches) { var parent = node.Parent; var tree1 = CreateTreeFromNode(random, node, rootSymbol, startSymbol); double min1 = 0.0, max1 = 0.0; foreach (double v in interpreter.GetSymbolicExpressionTreeValues(tree1, dataset, rows)) { if (min1 > v) { min1 = v; } if (max1 < v) { max1 = v; } } double behavioralDistance = (Math.Abs(min0 - min1) + Math.Abs(max0 - max1)) / 2; // this can be NaN of Infinity because some trees are crazy like exp(exp(exp(...))), we correct that below weights.Add(behavioralDistance); node.Parent = parent; // restore correct node parent } // remove branches with an infinite or NaN behavioral distance for (int i = weights.Count - 1; i >= 0; --i) { if (Double.IsNaN(weights[i]) || Double.IsInfinity(weights[i])) { weights.RemoveAt(i); allowedBranches.RemoveAt(i); } } // check if there are any allowed branches left if (allowedBranches.Count == 0) { return(parent0); } ISymbolicExpressionTreeNode selectedBranch; double sum = weights.Sum(); if (sum.IsAlmost(0.0) || weights.Count == 1) // if there is only one allowed branch, or if all weights are zero { selectedBranch = allowedBranches[0]; } else { for (int i = 0; i != weights.Count; ++i) // normalize and invert values { weights[i] = 1 - weights[i] / sum; } sum = weights.Sum(); // take new sum // compute the probabilities (selection weights) for (int i = 0; i != weights.Count; ++i) { weights[i] /= sum; } #pragma warning disable 612, 618 selectedBranch = allowedBranches.SelectRandom(weights, random); #pragma warning restore 612, 618 } Swap(crossoverPoint0, selectedBranch); return(parent0); }
public static void ReplaceRandomBranch(IRandom random, ISymbolicExpressionTree symbolicExpressionTree, int maxTreeLength, int maxTreeDepth) { var allowedSymbols = new List<ISymbol>(); ISymbolicExpressionTreeNode parent; int childIndex; int maxLength; int maxDepth; // repeat until a fitting parent and child are found (MAX_TRIES times) int tries = 0; do { #pragma warning disable 612, 618 parent = symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1).Where(n => n.SubtreeCount > 0).SelectRandom(random); #pragma warning restore 612, 618 childIndex = random.Next(parent.SubtreeCount); var child = parent.GetSubtree(childIndex); maxLength = maxTreeLength - symbolicExpressionTree.Length + child.GetLength(); maxDepth = maxTreeDepth - symbolicExpressionTree.Depth + child.GetDepth(); allowedSymbols.Clear(); foreach (var symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)) { // check basic properties that the new symbol must have if (symbol.Name != child.Symbol.Name && symbol.InitialFrequency > 0 && parent.Grammar.GetMinimumExpressionDepth(symbol) + 1 <= maxDepth && parent.Grammar.GetMinimumExpressionLength(symbol) <= maxLength) { allowedSymbols.Add(symbol); } } tries++; } while (tries < MAX_TRIES && allowedSymbols.Count == 0); if (tries < MAX_TRIES) { var weights = allowedSymbols.Select(s => s.InitialFrequency).ToList(); #pragma warning disable 612, 618 var seedSymbol = allowedSymbols.SelectRandom(weights, random); #pragma warning restore 612, 618 // replace the old node with the new node var seedNode = seedSymbol.CreateTreeNode(); if (seedNode.HasLocalParameters) seedNode.ResetLocalParameters(random); parent.RemoveSubtree(childIndex); parent.InsertSubtree(childIndex, seedNode); ProbabilisticTreeCreator.PTC2(random, seedNode, maxLength, maxDepth); } }
public static void ChangeNodeType(IRandom random, ISymbolicExpressionTree symbolicExpressionTree) { List<ISymbol> allowedSymbols = new List<ISymbol>(); ISymbolicExpressionTreeNode parent; int childIndex; ISymbolicExpressionTreeNode child; // repeat until a fitting parent and child are found (MAX_TRIES times) int tries = 0; do { #pragma warning disable 612, 618 parent = symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1).Where(n => n.SubtreeCount > 0).SelectRandom(random); #pragma warning restore 612, 618 childIndex = random.Next(parent.SubtreeCount); child = parent.GetSubtree(childIndex); int existingSubtreeCount = child.SubtreeCount; allowedSymbols.Clear(); foreach (var symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)) { // check basic properties that the new symbol must have if (symbol.Name != child.Symbol.Name && symbol.InitialFrequency > 0 && existingSubtreeCount <= parent.Grammar.GetMinimumSubtreeCount(symbol) && existingSubtreeCount >= parent.Grammar.GetMaximumSubtreeCount(symbol)) { // check that all existing subtrees are also allowed for the new symbol bool allExistingSubtreesAllowed = true; for (int existingSubtreeIndex = 0; existingSubtreeIndex < existingSubtreeCount && allExistingSubtreesAllowed; existingSubtreeIndex++) { var existingSubtree = child.GetSubtree(existingSubtreeIndex); allExistingSubtreesAllowed &= parent.Grammar.IsAllowedChildSymbol(symbol, existingSubtree.Symbol, existingSubtreeIndex); } if (allExistingSubtreesAllowed) { allowedSymbols.Add(symbol); } } } tries++; } while (tries < MAX_TRIES && allowedSymbols.Count == 0); if (tries < MAX_TRIES) { var weights = allowedSymbols.Select(s => s.InitialFrequency).ToList(); #pragma warning disable 612, 618 var newSymbol = allowedSymbols.SelectRandom(weights, random); #pragma warning restore 612, 618 // replace the old node with the new node var newNode = newSymbol.CreateTreeNode(); if (newNode.HasLocalParameters) newNode.ResetLocalParameters(random); foreach (var subtree in child.Subtrees) newNode.AddSubtree(subtree); parent.RemoveSubtree(childIndex); parent.InsertSubtree(childIndex, newNode); } }
private static void DoSpawn(WorldManager world, HashSet<int> chunksToSpawnIn, Mob[] mobEntities, List<WeightedValue<MobType>> mobGroup, int maximumMobs, bool inWater = false) { // Based on original server spawn logic and minecraft wiki (http://www.minecraftwiki.net/wiki/Spawn) // Check that we haven't already reached the maximum number of this type of mob if (mobGroup.Count > 0 && (mobEntities.Where(e => mobGroup.Where(mob => mob.Value == e.Type).Any()).Count() <= maximumMobs * chunksToSpawnIn.Count / 256)) { foreach (var packedChunk in chunksToSpawnIn) { MobType mobType = mobGroup.SelectRandom(world.Server.Rand); UniversalCoords packSpawnPosition = GetRandomPointInChunk(world, UniversalCoords.FromPackedChunkToX(packedChunk), UniversalCoords.FromPackedChunkToZ(packedChunk)); byte? blockId = world.GetBlockId(packSpawnPosition); if (blockId == null) continue; BlockBase blockClass = BlockHelper.Instance.CreateBlockInstance((byte)blockId); if (!blockClass.IsOpaque && ((!inWater && blockClass.Type == BlockData.Blocks.Air) || (inWater && blockClass.IsLiquid))) // Lava is Opaque, so IsLiquid is safe to use here for water & still water { int spawnedCount = 0; int x = packSpawnPosition.WorldX; int y = packSpawnPosition.WorldY; int z = packSpawnPosition.WorldZ; for (int i = 0; i < 21; i++) { // Every 4th attempt reset the coordinates to the centre of the pack spawn if (i % 4 == 0) { x = packSpawnPosition.WorldX; y = packSpawnPosition.WorldY; z = packSpawnPosition.WorldZ; } const int distance = 6; x += world.Server.Rand.Next(distance) - world.Server.Rand.Next(distance); y += world.Server.Rand.Next(1) - world.Server.Rand.Next(1); z += world.Server.Rand.Next(distance) - world.Server.Rand.Next(distance); if (CanMobTypeSpawnAtLocation(mobType, world, x, y, z)) { AbsWorldCoords spawnPosition = new AbsWorldCoords(x + 0.5, y, z + 0.5); // Check that no player is within a radius of 24 blocks of the spawnPosition if (world.GetClosestPlayer(spawnPosition, 24.0) == null) { // Check that the squared distance is more than 576 from spawn (24 blocks) if (spawnPosition.ToVector().DistanceSquared(new AbsWorldCoords(world.Spawn).ToVector()) > 576.0) { Mob newMob = MobFactory.Instance.CreateMob(world, world.Server, mobType) as Mob; if (newMob == null) break; newMob.Position = spawnPosition; newMob.Yaw = world.Server.Rand.NextDouble()*360.0; // Finally apply any mob specific rules about spawning here if (newMob.CanSpawnHere()) { //Event EntitySpawnEventArgs e = new EntitySpawnEventArgs(newMob, newMob.Position); world.Server.PluginManager.CallEvent(Event.EntitySpawn, e); if (e.EventCanceled) continue; newMob.Position = e.Location; //End Event ++spawnedCount; MobSpecificInitialisation(newMob, world, spawnPosition); world.Server.AddEntity(newMob); if (spawnedCount >= newMob.MaxSpawnedPerGroup) { // This chunk is full - move to the next break; } } } } } } } } } }