public static double Calculate(int iterations) { var random = new ThreadSafeRandom(); var inCircle = ParallelEnumerable.Range(0, iterations) // doesn't make sense to use more threads than we have processors .WithDegreeOfParallelism(Environment.ProcessorCount) .Select(_ => { double a, b; return Math.Sqrt((a = random.NextDouble()) * a + (b = random.NextDouble()) * b) <= 1; }) .Aggregate<bool, int, int>( 0, // Seed (agg, val) => val ? agg + 1 : agg, // Iterations (agg, subTotal) => agg + subTotal, // Aggregating subtotals result => result); // No projection of result needed return ((double)inCircle / iterations) * 4; }
public static double Calculate(int iterations) { var counterLockObject = new object(); int inCircle = 0; var random = new ThreadSafeRandom(); Parallel.For(0, iterations, // doesn't make sense to use more threads than we have processors new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, () => 0, (i, _, tLocal) => { #if LANG_EXPERIMENTAL // Note C# 6 declarating expression here return tLocal += Math.Sqrt((var a = random.NextDouble()) * a + (var b = random.NextDouble()) * b) <= 1 ? 1 : 0; #else double a, b; return tLocal += Math.Sqrt((a = random.NextDouble()) * a + (b = random.NextDouble()) * b) <= 1 ? 1 : 0; #endif }, subTotal => Interlocked.Add(ref inCircle, subTotal)); return ((double)inCircle / iterations) * 4; }
/// <summary> /// Generate a random number in the specified range. /// </summary> /// /// <param name="min">The minimum value.</param> /// <param name="max">The maximum value.</param> /// <returns>A random number.</returns> public static double Randomize(double min, double max) { double range = max - min; return((range * ThreadSafeRandom.NextDouble()) + min); }
public async Task <ClusterResult> ExecuteAsync(IRequestContext context, Func <IRequestContext, Task <ClusterResult> > next) { var counter = GetCounter(); counter.BeginRequest(); ClusterResult result; try { counter.AddRequest(); double ratio; double rejectionProbability; var metrics = counter.GetMetrics(); if (metrics.Requests >= options.MinimumRequests && (ratio = ComputeRatio(metrics)) >= options.CriticalRatio && (rejectionProbability = ComputeRejectionProbability(metrics, options)) > ThreadSafeRandom.NextDouble()) { LogThrottledRequest(context, ratio, rejectionProbability); return(ClusterResult.Throttled(context.Request)); } result = await next(context).ConfigureAwait(false); UpdateCounter(counter, result); } catch (OperationCanceledException) { if (context.CancellationToken.IsCancellationRequested) { counter.AddAccept(); } throw; } finally { counter.EndRequest(); } return(result); }
/// <summary> /// Perform a cross over. /// </summary> /// <param name="mom">The mother genome.</param> /// <param name="dad">The father genome.</param> /// <returns></returns> public new NEATGenome Crossover(NEATGenome mom, NEATGenome dad) { NEATParent best; // first determine who is more fit, the mother or the father? if (mom.Score == dad.Score) { if (mom.NumGenes == dad.NumGenes) { if (ThreadSafeRandom.NextDouble() > 0) { best = NEATParent.Mom; } else { best = NEATParent.Dad; } } else { if (mom.NumGenes < dad.NumGenes) { best = NEATParent.Mom; } else { best = NEATParent.Dad; } } } else { if (Comparator.IsBetterThan(mom.Score, dad.Score)) { best = NEATParent.Mom; } else { best = NEATParent.Dad; } } var babyNeurons = new Chromosome(); var babyGenes = new Chromosome(); var vecNeurons = new List <long>(); int curMom = 0; int curDad = 0; NEATLinkGene momGene; NEATLinkGene dadGene; NEATLinkGene selectedGene = null; while ((curMom < mom.NumGenes) || (curDad < dad.NumGenes)) { if (curMom < mom.NumGenes) { momGene = (NEATLinkGene)mom.Links.Get(curMom); } else { momGene = null; } if (curDad < dad.NumGenes) { dadGene = (NEATLinkGene)dad.Links.Get(curDad); } else { dadGene = null; } if ((momGene == null) && (dadGene != null)) { if (best == NEATParent.Dad) { selectedGene = dadGene; } curDad++; } else if ((dadGene == null) && (momGene != null)) { if (best == NEATParent.Mom) { selectedGene = momGene; } curMom++; } else if (momGene.InnovationId < dadGene.InnovationId) { if (best == NEATParent.Mom) { selectedGene = momGene; } curMom++; } else if (dadGene.InnovationId < momGene.InnovationId) { if (best == NEATParent.Dad) { selectedGene = dadGene; } curDad++; } else if (dadGene.InnovationId == momGene.InnovationId) { if (ThreadSafeRandom.NextDouble() < 0.5f) { selectedGene = momGene; } else { selectedGene = dadGene; } curMom++; curDad++; } if (babyGenes.Size() == 0) { babyGenes.Add(selectedGene); } else { if (((NEATLinkGene)babyGenes.Get(babyGenes.Size() - 1)) .InnovationId != selectedGene.InnovationId) { babyGenes.Add(selectedGene); } } // Check if we already have the nodes referred to in SelectedGene. // If not, they need to be added. AddNeuronID(selectedGene.FromNeuronID, vecNeurons); AddNeuronID(selectedGene.ToNeuronID, vecNeurons); } // end while // now create the required nodes. First sort them into order vecNeurons.Sort(); for (int i = 0; i < vecNeurons.Count; i++) { babyNeurons.Add(Innovations.CreateNeuronFromID( vecNeurons[i])); } // finally, create the genome var babyGenome = new NEATGenome(Population .AssignGenomeID(), babyNeurons, babyGenes, mom.InputCount, mom.OutputCount); babyGenome.GA = this; babyGenome.Population = Population; return(babyGenome); }
/// <summary> /// Perform one training iteration. /// </summary> public override void Iteration() { iteration++; IList <NEATGenome> newPop = new List <NEATGenome>(); int numSpawnedSoFar = 0; foreach (ISpecies s in Population.Species) { if (numSpawnedSoFar < Population.Size()) { var numToSpawn = (int)Math.Round(s.NumToSpawn); bool bChosenBestYet = false; while ((numToSpawn--) > 0) { NEATGenome baby = null; if (!bChosenBestYet) { baby = (NEATGenome)s.Leader; bChosenBestYet = true; } else { // if the number of individuals in this species is only // one // then we can only perform mutation if (s.Members.Count == 1) { // spawn a child baby = new NEATGenome((NEATGenome)s.ChooseParent()); } else { var g1 = (NEATGenome)s.ChooseParent(); if (ThreadSafeRandom.NextDouble() < paramCrossoverRate) { var g2 = (NEATGenome)s.ChooseParent(); int numAttempts = 5; while ((g1.GenomeID == g2.GenomeID) && ((numAttempts--) > 0)) { g2 = (NEATGenome)s.ChooseParent(); } if (g1.GenomeID != g2.GenomeID) { baby = Crossover(g1, g2); } } else { baby = new NEATGenome(g1); } } if (baby != null) { baby.GenomeID = Population.AssignGenomeID(); if (baby.Neurons.Size() < paramMaxPermittedNeurons) { baby.AddNeuron(paramChanceAddNode, paramNumTrysToFindOldLink); } // now there's the chance a link may be added baby.AddLink(paramChanceAddLink, paramChanceAddRecurrentLink, paramNumTrysToFindLoopedLink, paramNumAddLinkAttempts); // mutate the weights baby.MutateWeights(paramMutationRate, paramProbabilityWeightReplaced, paramMaxWeightPerturbation); baby.MutateActivationResponse( paramActivationMutationRate, paramMaxActivationPerturbation); } } if (baby != null) { // sort the baby's genes by their innovation numbers baby.SortGenes(); // add to new pop // if (newPop.contains(baby)) { // throw new EncogError("readd"); // } newPop.Add(baby); ++numSpawnedSoFar; if (numSpawnedSoFar == Population.Size()) { numToSpawn = 0; } } } } } while (newPop.Count < Population.Size()) { newPop.Add(TournamentSelection(Population.Size() / 5)); } Population.Clear(); foreach (NEATGenome genome in newPop) { Population.Add(genome); } ResetAndKill(); SortAndRecord(); SpeciateAndCalculateSpawnLevels(); }
private static double Random(double from, double to) => from + (to - from) * ThreadSafeRandom.NextDouble();
/// <summary> /// Mutate the genome by adding a link to this genome. /// </summary> /// /// <param name="mutationRate">The mutation rate.</param> /// <param name="chanceOfLooped">The chance of a self-connected neuron.</param> /// <param name="numTrysToFindLoop">The number of tries to find a loop.</param> /// <param name="numTrysToAddLink">The number of tries to add a link.</param> internal void AddLink(double mutationRate, double chanceOfLooped, int numTrysToFindLoop, int numTrysToAddLink) { // should we even add the link if (ThreadSafeRandom.NextDouble() > mutationRate) { return; } int countTrysToFindLoop = numTrysToFindLoop; int countTrysToAddLink = numTrysToFindLoop; // the link will be between these two neurons long neuron1ID = -1; long neuron2ID = -1; bool recurrent = false; // a self-connected loop? if (ThreadSafeRandom.NextDouble() < chanceOfLooped) { // try to find(randomly) a neuron to add a self-connected link to while ((countTrysToFindLoop--) > 0) { NEATNeuronGene neuronGene = ChooseRandomNeuron(false); // no self-links on input or bias neurons if (!neuronGene.Recurrent && (neuronGene.NeuronType != NEATNeuronType.Bias) && (neuronGene.NeuronType != NEATNeuronType.Input)) { neuron1ID = neuronGene.Id; neuron2ID = neuronGene.Id; neuronGene.Recurrent = true; recurrent = true; countTrysToFindLoop = 0; } } } else { // try to add a regular link while ((countTrysToAddLink--) > 0) { NEATNeuronGene neuron1 = ChooseRandomNeuron(true); NEATNeuronGene neuron2 = ChooseRandomNeuron(false); if (!IsDuplicateLink(neuron1ID, neuron2ID) && (neuron1.Id != neuron2.Id) && (neuron2.NeuronType != NEATNeuronType.Bias)) { neuron1ID = neuron1.Id; neuron2ID = neuron2.Id; break; } } } // did we fail to find a link if ((neuron1ID < 0) || (neuron2ID < 0)) { return; } // check to see if this innovation has already been tried NEATInnovation innovation = ((NEATTraining)GA).Innovations.CheckInnovation(neuron1ID, neuron1ID, NEATInnovationType .NewLink); // see if this is a recurrent(backwards) link var neuronGene_0 = (NEATNeuronGene)neuronsChromosome .Get(GetElementPos(neuron1ID)); if (neuronGene_0.SplitY > neuronGene_0.SplitY) { recurrent = true; } // is this a new innovation? if (innovation == null) { // new innovation ((NEATTraining)GA).Innovations .CreateNewInnovation(neuron1ID, neuron2ID, NEATInnovationType.NewLink); long id2 = GA.Population.AssignInnovationID(); var linkGene = new NEATLinkGene(neuron1ID, neuron2ID, true, id2, RangeRandomizer.Randomize(-1, 1), recurrent); linksChromosome.Add(linkGene); } else { // existing innovation var linkGene_1 = new NEATLinkGene(neuron1ID, neuron2ID, true, innovation.InnovationID, RangeRandomizer.Randomize(-1, 1), recurrent); linksChromosome.Add(linkGene_1); } }
// params // -f -s 5 -t 4 static void Main(string[] args) { // params EvolutionType et = EvolutionType.Tens; int startIndex = 0, count = 1, parallelDegreeExt = -1, parallelDegreeInt = -1; var rnd = new ThreadSafeRandom(); //char sep = Path.DirectorySeparatorChar; //string directoryPath = $"..{sep}..{sep}..{sep}AI{sep}Provincial{sep}data{sep}kingdoms{sep}"; //string directoryPath = $"..{sep}..{sep}..{sep}AI{sep}"; string directoryPath = BuyAgenda.DirectoryPath; string subsetFile = null; BuyAgendaManager manager = new SimpleManager(directoryPath, "Tens_"); IEnumerator <string> kingdoms = null; // params handling for (int i = 0; i < args.Length; i++) { if (args[i][0] != '-') { continue; } for (int j = 1; j < args[i].Length; j++) { try { switch (args[i][j]) { case 'c': count = int.Parse(args[++i]); break; case 'd': et = EvolutionType.Tens; manager = new SimpleManager(directoryPath, "Tens_"); break; case 'f': et = EvolutionType.Subsets; //manager = new CachedManager(directoryPath, 5, "Fives_"); manager = new SimpleManager(directoryPath, "Fives_"); subsetFile = "fives"; break; case 'h': et = EvolutionType.Subsets; //manager = new CachedManager(directoryPath, 3, "Threes_"); manager = new SimpleManager(directoryPath, "Threes43_"); // TODO 43 subsetFile = "threes"; break; case 'n': et = EvolutionType.NamedGames; break; case 's': startIndex = int.Parse(args[++i]); break; case 't': parallelDegreeExt = 1; parallelDegreeInt = int.Parse(args[++i]); break; default: break; } } catch { WriteLine($"Parameter {i} failed."); } } } WriteLine($"evolution: {et.ToString()}"); if (et == EvolutionType.Subsets) { kingdoms = File.ReadAllLines($"{directoryPath}{BuyAgenda.sep}{subsetFile}.txt").Skip(startIndex).Take(count).GetEnumerator(); WriteLine($"count: {count}"); WriteLine($"start index: {startIndex}"); } else { WriteLine($"kingdom: random"); } for (int i = 0; i < count; i++) { // try { switch (et) { case EvolutionType.Tens: { //cards = PresetGames.Get(Games.FirstGame).AddRequiredCards(); List <Card> cards = null; // get random 10 cards cards = Enumerable.Range((int)CardType.Adventurer, 25) .Select(t => ((t, r: rnd.NextDouble()))) .OrderBy(a => a.r) .Take(10) .Select(((int type, double)a) => Card.Get((CardType)a.type)) .ToList(); var kingdomName = cards.OrderBy(p => p.Type).Select(p => (int)p.Type).Aggregate("kingdom", (a, b) => a + " " + b); WriteLine($"kingdom {i}: {kingdomName}"); if (manager.Load(cards) != null) { WriteLine($"Skipping kingdom."); continue; } var evolution = new Evolution(new Params { Kingdom = cards, Evaluator = new ProvincialEvaluator(), ParallelDegreeExt = parallelDegreeExt, ParallelDegreeInt = parallelDegreeInt, LeaderCount = 10, PoolCount = 50, Generations = 50, }, new Logger()); var agenda = evolution.Run(); manager.Save(cards, agenda); } break; case EvolutionType.Subsets: { List <Card> cards = null; kingdoms.MoveNext(); cards = kingdoms.Current.Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries) .Select(a => Card.Get((CardType)int.Parse(a))).ToList(); var kingdomName = cards.OrderBy(p => p.Type).Select(p => (int)p.Type).Aggregate("kingdom", (a, b) => a + " " + b); WriteLine($"kingdom {i}: {kingdomName}"); if (manager.Load(cards) != null) { WriteLine("skipping"); continue; } var evolution = new Evolution(new Params { Kingdom = cards, Evaluator = new ProvincialEvaluator(), ParallelDegreeExt = parallelDegreeExt, ParallelDegreeInt = parallelDegreeInt, LeaderCount = 10, PoolCount = 50, Generations = 50, }, new Logger()); var agenda = evolution.Run(); manager.Save(cards, agenda); } break; case EvolutionType.NamedGames: { //cards = PresetGames.Get(Games.FirstGame).AddRequiredCards(); List <(List <Card> Cards, string Name)> games = new List <(List <Card>, string)> { (PresetGames.Get(Games.BigMoney), "bigMoneyGame"), (PresetGames.Get(Games.Interaction), "interaction"), (PresetGames.Get(Games.FirstGame), "firstGame"), (PresetGames.Get(Games.SizeDistortion), "sizeDistortion"), (PresetGames.Get(Games.ThrashHeap), "trasheap"), (PresetGames.Get(Games.VillageSquare), "village"), //((new int[]{ 9, 12, 15, 18, 22, 24, 27, 28, 31, 32}.Select(c => Card.Get((CardType)c)).ToList()), "badCards") //(new List<Card>{Card.Get(CardType.Curse)}, "bigMoney") }; games.ForEach(item => { var kingdomName = item.Cards.OrderBy(p => p.Type).Select(p => (int)p.Type).Aggregate("kingdom", (a, b) => a + " " + b); WriteLine($"kingdom {i}: {item.Name} {kingdomName}"); var evolution = new Evolution(new Params { Kingdom = item.Cards, Evaluator = new ProvincialEvaluator(), LeaderCount = 10, PoolCount = 50, Generations = 50, }, new Logger()); //manager.First(a => a.Id == item.Name)); var agenda = evolution.Run(); manager.Save(item.Cards, agenda); }); } break; default: break; } } //catch (Exception e) //{ // WriteLine(e.Message); //} } ReadLine(); }
private static Ability Transient() { return(new Ability { Name = "Transient", Cooldown = 6, Type = Ability.Types.AbilityType.Offensive, ModelMetadata = new ModelMetadata { JsAssetPath = "npc/4eb50ec0-501e-4a4d-9935-48f1456d6b3f/abilities/0/ab_3040063000_01.js", ConstructorName = "mc_ab_3040063000_01_effect", ImageAssets = { new ImageAsset { Name = "ab_3040063000_01", Path = "npc/4eb50ec0-501e-4a4d-9935-48f1456d6b3f/abilities/0/ab_3040063000_01.png", }, }, }, ProcessEffects = (narmaya, targetPositionInFrontline, raidActions) => { new MultihitDamage { Element = Element.Dark, DamageModifier = (narmaya.Hero.Level >= 95 ? 4 : 3) + (ThreadSafeRandom.NextDouble() * 0.5), DamageCap = narmaya.Hero.Level >= 95 ? 480000 : 430000, HitNumber = 1, }.ProcessEffects(narmaya, targetPositionInFrontline, raidActions); var hasGlasswingWaltzEffect = narmaya.GetStatusEffect(GlasswingWaltzId) != null; if (narmaya.GlobalState[DawnflyDance].BooleanValue || hasGlasswingWaltzEffect) { narmaya.ApplyStatusEffectsFromTemplate( new StatusEffectSnapshot { TurnDuration = 3, }, raidActions, (StatusEffectLibrary.DoubleAttackRateUpNpc, ModifierLibrary.FlatDoubleAttackRateBoost, narmaya.Hero.Level >= 95 ? double.PositiveInfinity : 25), (StatusEffectLibrary.TripleAttackRateUpNpc, ModifierLibrary.FlatTripleAttackRateBoost, narmaya.Hero.Level >= 95 ? 10 : 5)); } if (!narmaya.GlobalState[DawnflyDance].BooleanValue || hasGlasswingWaltzEffect) { var target = narmaya.ResolveEnemyTarget(targetPositionInFrontline); if (target != null && target.IsAlive()) { var strength = -25; if (narmaya.Hero.Rank < 95) { if (target.ChargeDiamonds == 0) { strength = -7; } else if (target.ChargeDiamonds == 1) { strength = -14; } else if (target.ChargeDiamonds == 2) { strength = -21; } else { strength = -25; } } target.ApplyStatusEffect( new StatusEffectSnapshot { Id = StatusEffectLibrary.DefenseDownNpc, RemainingDurationInSeconds = 180, Strength = strength, BaseAccuracy = 95, }, raidActions); } } if (hasGlasswingWaltzEffect) { narmaya.RemoveStatusEffect(GlasswingWaltzId); } }, AnimationName = "ab_motion", ShouldRepositionSpriteAnimation = true, RepositionOnTarget = true, });
public override void AfterDatabaseInitialized() { base.AfterDatabaseInitialized(); var dbc = AppConfig.DatabaseCreation; var colors = ColorDataProvider.GetList().ToArray(); var models = BikeModelDataProvider.GetList().ToArray(); var user = UserDataProvider.GetByUserName(dbc.AdminUserEmail, true); for (int i = 0; i < dbc.TestBikesCount; i++) { var available = ThreadSafeRandom.NextBool(); BikeDataProvider.Add(new Bike( 0, available ? BikeState.Available: ThreadSafeRandom.NextItem(new[] { BikeState.Reserved, BikeState.Reserved, BikeState.Reserved, BikeState.Reserved, BikeState.Reserved, BikeState.Reserved, BikeState.Reserved, BikeState.Reserved, BikeState.Lost, BikeState.Maintenance }), ThreadSafeRandom.NextItem(models), ThreadSafeRandom.NextItem(colors), // put around Érd? ThreadSafeRandom.Next(10) == 0 ? new Location(Hungary_Pest_Erd.Lat + ThreadSafeRandom.NextDouble(-1d, 1d), Hungary_Pest_Erd.Lng + ThreadSafeRandom.NextDouble(-1d, 1d), true) : new Location(ThreadSafeRandom.NextDouble(-90d, 90d), ThreadSafeRandom.NextDouble(-180d, 180d), true) , ThreadSafeRandom.NextItem(new[] { "San Francisco", "New York", "Paris", "Budapest", "Berlin", "Tokyo", "Washington", "Dallas", "Houston", "London", "Madrid", "Rome", "Lisbon", "Vien", "Beijing", "Melbourne", "Sydney", "Rio", "Amsterdam", "Gant", "Brussels", "Moscow", "Delhi", "Genova", "Ottawa", "Mexico City", "Los Angeles", "Las Vegas" }), DateTime.UtcNow.AddMinutes(available ? ThreadSafeRandom.Next(-30 * 24 * 60, 0) : ThreadSafeRandom.Next(1, 5 * 24 * 60)), (float)ThreadSafeRandom.NextDouble(0d, 5d), DateTime.UtcNow, user, null, null, false )); } }
public Spectrum Li(Ray ray, Scene s) { var L = Spectrum.ZeroSpectrum; var beta = Spectrum.Create(1.0); bool specularBounce = false; for (int nBounces = 0; nBounces < 20; nBounces++) { (double?d, SurfaceInteraction si) = s.Intersect(ray); Vector3 wo = -ray.d; if (nBounces == 0 || specularBounce) { if (d != null) { L.AddTo(beta * si.Le(wo)); } else { foreach (var light in s.Lights) { L.AddTo(beta * Spectrum.ZeroSpectrum); // light.Le() } } } if (d == null) { break; } if (si.Obj is Light) { //if (nBounces == 0) //{ // L.AddTo(beta * si.Le(wo)); //} break; } if (!specularBounce) { L.AddTo(beta * Light.UniformSampleOneLight(si, s)); } (Spectrum f, Vector3 wiW, double pdf, bool bxdfIsSpecular) = ((Shape)si.Obj).BSDF.Sample_f(wo, si); specularBounce = bxdfIsSpecular; if (f.IsBlack() || pdf == 0) { break; } var wi = si.SpawnRay(wiW); beta = beta * f * Vector3.AbsDot(wiW, si.Normal) / pdf; ray = wi; if (nBounces > 3) { double q = 1 - beta.Max(); if (ThreadSafeRandom.NextDouble() < q) { break; } beta = beta / (1 - q); } } return(L); }
public static void Train(string udSource, string ontonotesSource) { var trainFiles = Directory.GetFiles(udSource, "*-train.conllu", SearchOption.AllDirectories); var testFiles = Directory.GetFiles(udSource, "*-dev.conllu", SearchOption.AllDirectories); List <string> trainFilesOntonotesEnglish = null; if (!string.IsNullOrWhiteSpace(ontonotesSource)) { trainFilesOntonotesEnglish = Directory.GetFiles(ontonotesSource, "*.parse.ddg", SearchOption.AllDirectories) .Where(fn => !fn.Contains("sel_") || int.Parse(Path.GetFileNameWithoutExtension(fn).Split(new char[] { '_', '.' }).Skip(1).First()) < 3654) .ToList(); } var trainFilesPerLanguage = trainFiles.Select(f => new { lang = Path.GetFileNameWithoutExtension(f).Replace("_", "-").Split(new char[] { '-' }).First(), file = f }).GroupBy(f => f.lang).ToDictionary(g => g.Key, g => g.Select(f => f.file).ToList()); var testFilesPerLanguage = testFiles.Select(f => new { lang = Path.GetFileNameWithoutExtension(f).Replace("_", "-").Split(new char[] { '-' }).First(), file = f }).GroupBy(f => f.lang).ToDictionary(g => g.Key, g => g.Select(f => f.file).ToList()); var languages = trainFilesPerLanguage.Keys.ToList(); Logger.LogInformation($"Found these languages for training: {string.Join(", ", languages)}"); int N_training = 5; Parallel.ForEach(languages, lang => { Language language; try { language = Languages.CodeToEnum(lang); } catch { Logger.LogWarning($"Unknown language {lang}"); return; } var arcNames = new HashSet <string>(); if (trainFilesPerLanguage.TryGetValue(lang, out var langTrainFiles) && testFilesPerLanguage.TryGetValue(lang, out var langTestFiles)) { var trainDocuments = ReadCorpus(langTrainFiles, arcNames, language); var testDocuments = ReadCorpus(langTestFiles, arcNames, language); if (language == Language.English) { //Merge with Ontonotes 5.0 corpus trainDocuments.AddRange(ReadCorpus(trainFilesOntonotesEnglish, arcNames, language, isOntoNotes: true)); } double bestScore = double.MinValue; for (int i = 0; i < N_training; i++) { var Tagger = new AveragePerceptronTagger(language, 0); Tagger.Train(trainDocuments.AsEnumerable(), (int)(5 + ThreadSafeRandom.Next(15))); var scoreTrain = TestTagger(trainDocuments, Tagger); var scoreTest = TestTagger(testDocuments, Tagger); if (scoreTest > bestScore) { Logger.LogInformation($"\n>>>>> {lang}: NEW POS BEST: {scoreTest:0.0}%"); try { Tagger.StoreAsync().Wait(); } catch (Exception E) { Logger.LogError(E, $"\n>>>>> {lang}: Failed to store model"); } bestScore = scoreTest; } else { Logger.LogInformation($"\n>>>>> {lang}: POS BEST IS STILL : {bestScore:0.0}%"); } } bestScore = double.MinValue; for (int i = 0; i < N_training; i++) { var Parser = new AveragePerceptronDependencyParser(language, 0 /*, arcNames.ToList()*/); try { Parser.Train(trainDocuments.AsEnumerable(), (int)(5 + ThreadSafeRandom.Next(10)), (float)(1D - ThreadSafeRandom.NextDouble() * ThreadSafeRandom.NextDouble())); } catch (Exception E) { Logger.LogInformation("FAIL: " + E.Message); continue; } trainDocuments = ReadCorpus(langTrainFiles, arcNames, language); testDocuments = ReadCorpus(langTestFiles, arcNames, language); if (language == Language.English) { //Merge with Ontonotes 5.0 corpus trainDocuments.AddRange(ReadCorpus(trainFilesOntonotesEnglish, arcNames, language, isOntoNotes: true)); } var scoreTrain = TestParser(trainDocuments, Parser); var scoreTest = TestParser(testDocuments, Parser); if (scoreTest > bestScore) { Logger.LogInformation($"\n>>>>> {lang}: NEW DEP BEST: {scoreTest:0.0}%"); try { Parser.StoreAsync().Wait(); } catch (Exception E) { Logger.LogError(E, $"\n>>>>> {lang}: Failed to store model"); } bestScore = scoreTest; } else { Logger.LogInformation($"\n>>>>> {lang}: DEP BEST IS STILL : {bestScore:0.0}%"); } Parser = null; } } }); foreach (var lang in languages) { Language language; try { language = Languages.CodeToEnum(lang); } catch { Logger.LogInformation($"Unknown language {lang}"); return; } var arcNames = new HashSet <string>(); var trainDocuments = ReadCorpus(trainFilesPerLanguage[lang], arcNames, language); var testDocuments = ReadCorpus(testFilesPerLanguage[lang], arcNames, language); if (language == Language.English) { //Merge with Ontonotes 5.0 corpus var ontonotesDocuments = ReadCorpus(trainFilesOntonotesEnglish, arcNames, language, isOntoNotes: true); trainDocuments.AddRange(ontonotesDocuments); } var Tagger = AveragePerceptronTagger.FromStoreAsync(language, 0, "").WaitResult(); Logger.LogInformation($"\n{lang} - TAGGER / TRAIN"); TestTagger(trainDocuments, Tagger); Logger.LogInformation($"\n{lang} - TAGGER / TEST"); TestTagger(testDocuments, Tagger); trainDocuments = ReadCorpus(trainFilesPerLanguage[lang], arcNames, language); testDocuments = ReadCorpus(testFilesPerLanguage[lang], arcNames, language); var Parser = AveragePerceptronDependencyParser.FromStoreAsync(language, 0, "").WaitResult(); Logger.LogInformation($"\n{lang} - PARSER / TRAIN"); TestParser(trainDocuments, Parser); Logger.LogInformation($"\n{lang} - PARSER / TEST"); TestParser(testDocuments, Parser); } }
public void Synapsis(int node, int connection) { _layer.KnowlodgeMatrix[node, connection] = (float)_tr.NextDouble(); }
/// <summary> /// Generate a random string, of a specified length. This /// is used to generate the multipart boundary. /// </summary> /// <returns>A random string.</returns> protected static String RandomString() { return("" + ThreadSafeRandom.NextDouble()); }
public override List <Point> getNextStep() { List <Point> res = new List <Point>(); int pi = 0; List <Point> nextLeft = new List <Point>(); List <Point> nextRight = new List <Point>(); foreach (Point p in od) { if (rightPoints.Contains(p)) { rightPoints.Remove(p); addIfLegal(nextRight, p.add(-1, 0)); } else if (leftPoints.Contains(p)) { leftPoints.Remove(p); addIfLegal(nextLeft, p.add(1, 0)); } else { // add to at least one direction if (myRand.NextDouble() < dualSearchProb) { addIfLegal(nextLeft, p.add(1, 0)); addIfLegal(nextRight, p.add(-1, 0)); } else { if (myRand.NextDouble() < 0.5) { addIfLegal(nextLeft, p.add(1, 0)); } else { addIfLegal(nextRight, p.add(-1, 0)); } } } } // with some probability, add a point even if it failed, anyway: foreach (Point failedPoint in leftPoints) { if (!od.Contains(failedPoint)) // if od contains it, we already added the point to nextLeft { if (myRand.NextDouble() > stopScanProb) { addIfLegal(nextLeft, failedPoint.add(1, 0)); } } } foreach (Point failedPoint in rightPoints) { if (!od.Contains(failedPoint)) { if (myRand.NextDouble() > stopScanProb) { addIfLegal(nextRight, failedPoint.add(-1, 0)); } } } leftPoints = nextLeft; rightPoints = nextRight; if (leftPoints.Count + rightPoints.Count < param.A_P.Count) { int addToLeft = Math.Min(param.A_P.Count - (leftPoints.Count + rightPoints.Count), waitingLeftPoints.Count); for (int i = 0; i < addToLeft; ++i) { leftPoints.Add(waitingLeftPoints.Last()); waitingLeftPoints.RemoveAt(waitingLeftPoints.Count() - 1); } if (leftPoints.Count + rightPoints.Count < param.A_P.Count) { int addToRight = Math.Min(param.A_P.Count - (leftPoints.Count + rightPoints.Count), waitingRightPoints.Count); for (int i = 0; i < addToRight; ++i) { waitingRightPoints.Add(waitingRightPoints.Last()); waitingRightPoints.RemoveAt(waitingRightPoints.Count() - 1); } } } res.AddRange(leftPoints); res.AddRange(rightPoints); pi = res.Count(); for (; pi < param.A_P.Count; ++pi) { Point p; do { p = new Point((int)(myRand.Next() % graph.WidthCellCount), (int)(myRand.Next() % graph.HeightCellCount)); }while (res.Contains(p)); res.Add(p); } return(res); }
/// <summary> /// Generate next random number. /// </summary> /// /// <returns>Returns next random number.</returns> /// public float Next( ) { return((float)rand.NextDouble( )); }
private static Ability VorpalRage() { return(new Ability { Name = "Vorpal Rage", Cooldown = 4, Type = Ability.Types.AbilityType.Offensive, ModelMetadata = new ModelMetadata { JsAssetPath = "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/abilities/4/ab_3040032000_04.js", ConstructorName = "mc_ab_3040032000_04_effect", ImageAssets = { new ImageAsset { Name = "ab_3040032000_04", Path = "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/abilities/4/ab_3040032000_04.png", }, }, }, ProcessEffects = (threo, targetPositionInFrontline, raidActions) => { new MultihitDamage { Element = Element.Earth, DamageModifier = (threo.Hero.Level >= 55 ? 2 : 1.5) + (ThreadSafeRandom.NextDouble() * 0.5), DamageCap = 620_000, HitNumber = 1, }.ProcessEffects(threo, targetPositionInFrontline, raidActions); // TODO: drain if (threo.GlobalState["::axe_form"].BooleanValue) { threo.ApplyStatusEffect( new StatusEffectSnapshot { Id = Wrath, TurnDuration = 5, }, raidActions); threo.Heal(threo.HpPercentage < 25 ? 3000 : 1500, raidActions); threo.ApplyStatusEffectsFromTemplate( new StatusEffectSnapshot { IsUsedInternally = true, TurnDuration = 5, TriggerCondition = new TriggerCondition { Type = TriggerCondition.Types.Type.HasStatusEffect, Data = Wrath, }, }, (Wrath + "/da_up", ModifierLibrary.FlatDoubleAttackRateBoost, 25), (Wrath + "/ta_up", ModifierLibrary.FlatTripleAttackRateBoost, 15)); if (threo.Hero.Level >= 90) { threo.ApplyStatusEffect(new StatusEffectSnapshot { Id = Wrath + "/crit", IsUsedInternally = true, TurnDuration = 5, TriggerCondition = new TriggerCondition { Type = TriggerCondition.Types.Type.HasStatusEffect, Data = Wrath, }, Strength = 30, Modifier = ModifierLibrary.FlatCriticalHitRateBoost, ExtraData = new CriticalHit { DamageMultiplier = 0.5, }.ToByteString(), }); } } else if (threo.GetStatusEffect(Wrath) != null) { threo.ApplyStatusEffect( new StatusEffectSnapshot { Id = Agitation, TurnDuration = 5, }, raidActions); threo.ApplyStatusEffectsFromTemplate( new StatusEffectSnapshot { IsUsedInternally = true, TurnDuration = 5, TriggerCondition = new TriggerCondition { Type = TriggerCondition.Types.Type.HasStatusEffect, Data = Agitation, }, }, (Agitation + "/ca_up", ModifierLibrary.FlatChargeAttackDamageBoost, 15), (Agitation + "/cb_up", ModifierLibrary.FlatChainBurstDamageBoost, 15)); if (threo.Hero.Level >= 90) { threo.ApplyStatusEffect(new StatusEffectSnapshot { Id = Agitation + "/echo", IsUsedInternally = true, TurnDuration = 5, TriggerCondition = new TriggerCondition { Type = TriggerCondition.Types.Type.HasStatusEffect, Data = Wrath, }, Strength = 70, Modifier = ModifierLibrary.AdditionalDamage, AttackElementRestriction = Element.Earth, }); } } },
/// <summary> /// Mutate the genome by adding a neuron. /// </summary> /// /// <param name="mutationRate">The mutation rate.</param> /// <param name="numTrysToFindOldLink">The number of tries to find a link to split.</param> internal void AddNeuron(double mutationRate, int numTrysToFindOldLink) { // should we add a neuron? if (ThreadSafeRandom.NextDouble() > mutationRate) { return; } int countTrysToFindOldLink = numTrysToFindOldLink; // the link to split NEATLinkGene splitLink = null; int sizeBias = inputCount + outputCount + 10; // if there are not at least int upperLimit; if (linksChromosome.Size() < sizeBias) { upperLimit = NumGenes - 1 - (int)Math.Sqrt(NumGenes); } else { upperLimit = NumGenes - 1; } while ((countTrysToFindOldLink--) > 0) { // choose a link, use the square root to prefer the older links int i = RangeRandomizer.RandomInt(0, upperLimit); var link = (NEATLinkGene)linksChromosome .Get(i); // get the from neuron long fromNeuron = link.FromNeuronID; if ((link.Enabled) && (!link.Recurrent) && (((NEATNeuronGene)Neurons.Get( GetElementPos(fromNeuron))).NeuronType != NEATNeuronType.Bias)) { splitLink = link; break; } } if (splitLink == null) { return; } splitLink.Enabled = false; double originalWeight = splitLink.Weight; long from = splitLink.FromNeuronID; long to = splitLink.ToNeuronID; var fromGene = (NEATNeuronGene)Neurons.Get( GetElementPos(from)); var toGene = (NEATNeuronGene)Neurons.Get( GetElementPos(to)); double newDepth = (fromGene.SplitY + toGene.SplitY) / 2; double newWidth = (fromGene.SplitX + toGene.SplitX) / 2; // has this innovation already been tried? NEATInnovation innovation = ((NEATTraining)GA).Innovations.CheckInnovation(from, to, NEATInnovationType .NewNeuron); // prevent chaining if (innovation != null) { long neuronID = innovation.NeuronID; if (AlreadyHaveThisNeuronID(neuronID)) { innovation = null; } } if (innovation == null) { // this innovation has not been tried, create it long newNeuronID = ((NEATTraining)GA).Innovations.CreateNewInnovation(from, to, NEATInnovationType. NewNeuron, NEATNeuronType. Hidden, newWidth, newDepth); neuronsChromosome.Add(new NEATNeuronGene( NEATNeuronType.Hidden, newNeuronID, newDepth, newWidth)); // add the first link long link1ID = (GA).Population.AssignInnovationID(); ((NEATTraining)GA).Innovations .CreateNewInnovation(from, newNeuronID, NEATInnovationType.NewLink); var link1 = new NEATLinkGene(from, newNeuronID, true, link1ID, 1.0d, false); linksChromosome.Add(link1); // add the second link long link2ID = (GA).Population.AssignInnovationID(); ((NEATTraining)GA).Innovations .CreateNewInnovation(newNeuronID, to, NEATInnovationType.NewLink); var link2 = new NEATLinkGene(newNeuronID, to, true, link2ID, originalWeight, false); linksChromosome.Add(link2); } else { // existing innovation long newNeuronID_0 = innovation.NeuronID; NEATInnovation innovationLink1 = ((NEATTraining)GA).Innovations.CheckInnovation(from, newNeuronID_0, NEATInnovationType . NewLink); NEATInnovation innovationLink2 = ((NEATTraining)GA).Innovations.CheckInnovation(newNeuronID_0, to, NEATInnovationType.NewLink); if ((innovationLink1 == null) || (innovationLink2 == null)) { throw new NeuralNetworkError("NEAT Error"); } var link1_1 = new NEATLinkGene(from, newNeuronID_0, true, innovationLink1.InnovationID, 1.0d, false); var link2_2 = new NEATLinkGene(newNeuronID_0, to, true, innovationLink2.InnovationID, originalWeight, false); linksChromosome.Add(link1_1); linksChromosome.Add(link2_2); var newNeuron = new NEATNeuronGene( NEATNeuronType.Hidden, newNeuronID_0, newDepth, newWidth); neuronsChromosome.Add(newNeuron); } return; }
public static Hero NewInstance() { return(new Hero { Id = ByteString.CopyFrom(Id.ToByteArray()), Name = "Threo", Races = { Race.Draph }, Gender = Gender.Female, MaxAttack = 13333, AttackLevels = { 11333 }, MaxHp = 1833, HpLevels = { 1533 }, MaxLevel = 100, BaseDoubleAttackRate = 6, BaseTripleAttackRate = 4.5, Element = Element.Earth, WeaponProficiencies = { EquipmentType.Axe, EquipmentType.Sword }, AvailablePerkIds = { ExtendedMasteryPerks.AttackBoost, ExtendedMasteryPerks.DefenseBoost, ExtendedMasteryPerks.DoubleAttackRateBoost, ExtendedMasteryPerks.CriticalHitRateBoost, ExtendedMasteryPerks.ChargeAttackDamageBoost, ExtendedMasteryPerks.AttackBoost, ExtendedMasteryPerks.DefenseBoost, ExtendedMasteryPerks.HpBoost, ExtendedMasteryPerks.CriticalHitRateBoost, ExtendedMasteryPerks.WaterDamageReduction, ExtendedMasteryPerks.AttackBoostAndDefenseDown, ExtendedMasteryPerks.AttackBoostAndDefenseDown, ExtendedMasteryPerks.ChargeAttackDamageBoost, ExtendedMasteryPerks.ChargeAttackDamageCapBoost, ExtendedMasteryPerks.SupportSkill, }, PassiveAbilities = { new PassiveAbility { Type = PassiveAbility.Types.PassiveAbilityType.SupportSkill, Name = "Passive ability 1", Description = "Passive ability 1 description", }, new PassiveAbility { Type = PassiveAbility.Types.PassiveAbilityType.SupportSkill, Name = "Passive ability 2", Description = "Passive ability 2 description", }, }, UpgradedPassiveAbilities = { new PassiveAbilityUpgrade { Ability = new PassiveAbility { Type = PassiveAbility.Types.PassiveAbilityType.SupportSkill, Name = "Upgraded passive ability 2", Description = "Upgraded passive ability 2 description", }, RequiredLevel = 85, RequiredRank = 5, UpgradedPassiveAbilityIndex = 2, }, new PassiveAbilityUpgrade { Ability = new PassiveAbility { Type = PassiveAbility.Types.PassiveAbilityType.SupportSkill, Name = "Passive ability 3", Description = "Passive ability 3 description", }, RequiredLevel = 95, RequiredRank = 5, UpgradedPassiveAbilityIndex = 3, }, }, ModelMetadata = { AxeFormModel, }, OnHitEffectModelMetadata = { AxeFormOnHitModel, }, SpecialAbility = new SpecialAbility { Name = string.Empty, HitCount = { 1 }, ModelMetadata = { AxeFormChargeAttackModel, }, Effects = { }, ProcessEffects = (threo, raidActions) => { if (threo.GlobalState["::axe_form"].BooleanValue) { threo.GlobalState["::axe_form"].BooleanValue = false; threo.ApplyStatusEffect( new StatusEffectSnapshot { Id = StatusEffectLibrary.EarthAttackUpNpc, Strength = 20, TurnDuration = 4, }, raidActions); threo.PlayAnimation("change_1", raidActions); threo.ChangeForm( new ModelMetadata { JsAssetPath = "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/model/0/npc_3040032000_03_f1.js", ConstructorName = "mc_npc_3040032000_03_f1", ImageAssets = { new ImageAsset { Name = "npc_3040032000_03_f1", Path = "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/model/0/npc_3040032000_03_f1.png", }, }, }, raidActions, onHitEffectModel: new ModelMetadata { JsAssetPath = "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/model/0/phit_3040032000_03_f1.js", ConstructorName = "mc_phit_3040032000_03_f1_effect", ImageAssets = { new ImageAsset { Name = "phit_3040032000_03_f1", Path = "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/model/0/phit_3040032000_03_f1.png", }, }, }, specialAbility: new SpecialAbility { HitCount = { 2 }, ModelMetadata = { new ModelMetadata { JsAssetPath = "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/model/0/nsp_3040032000_03_f1.js", ConstructorName = "mc_nsp_3040032000_03_f1_special", ImageAssets = { new ImageAsset { Name = "nsp_3040032000_03_f1", Path = "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/model/0/nsp_3040032000_03_f1.png", }, }, }, }, ShouldRepositionSpriteAnimationOnTarget = true, }); threo.ChangeAbilityIcon(1, "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/abilities/1a.png"); } else { threo.GlobalState["::axe_form"].BooleanValue = true; MeteorThrust().Cast(threo, raidActions); threo.PlayAnimation("change_2", raidActions); threo.ChangeForm( AxeFormModel, raidActions, onHitEffectModel: AxeFormOnHitModel, specialAbility: new SpecialAbility { HitCount = { 1 }, ModelMetadata = { AxeFormChargeAttackModel, }, ShouldRepositionSpriteAnimationOnTarget = true, }); threo.ChangeAbilityIcon(1, "npc/612d0c88-d7ef-43ec-bf20-7d630c7c5200/abilities/1.png"); } }, ShouldRepositionSpriteAnimationOnTarget = true, }, Abilities = { VorpalRage(), BerserkForge(cooldown: 7), GroundZero(cooldown: 8), }, UpgradedAbilities = { new AbilityUpgrade { RequiredLevel = 85, Ability = BerserkForge(cooldown: 6), UpgradedAbilityIndex = 1, }, new AbilityUpgrade { RequiredLevel = 95, Ability = GroundZero(cooldown: 7), UpgradedAbilityIndex = 2, }, new AbilityUpgrade { RequiredLevel = 100, Ability = ThreeTigerBlessing(0), UpgradedAbilityIndex = 3, }, }, OnAttackEnd = (threo, attackResult, raidActions) => { if (!threo.IsAlive() || threo.PositionInFrontline >= 4 || (attackResult != EntitySnapshot.AttackResult.Single && attackResult != EntitySnapshot.AttackResult.Double && attackResult != EntitySnapshot.AttackResult.Triple && attackResult != EntitySnapshot.AttackResult.MultiAttack)) { return; } var supportSkillRank = threo.Hero.GetSupportSkillRank(); if (supportSkillRank > 0 && ThreadSafeRandom.NextDouble() < (1 + supportSkillRank) * 0.025) { threo.ApplyStatusEffect( new StatusEffectSnapshot { Id = "threo/atk_up", TurnDuration = int.MaxValue, IsStackable = true, Strength = 10, Modifier = ModifierLibrary.FlatAttackBoost, StackingCap = 30, }, raidActions); } }, OnSetup = (threo, allies, loadout) => { threo.GlobalState.Add("::axe_form", TypedValue.FromBool(true)); if (threo.Hero.Level >= 95) { // 20% boost to damage against Water foes, non stackable with Seraphic effects from weapons threo.OverrideWeaponSeraphicModifier(20); } }, }); }
public static Ability Thunder(Element damageElement) { return(new Ability { Name = "Thunder", Description = string.Empty, Cooldown = 6, Type = Ability.Types.AbilityType.Offensive, ModelMetadata = new ModelMetadata { ConstructorName = "mc_ab_all_3040078000_03", JsAssetPath = "npc/60d4c46a-f1bd-4d11-b39b-e18835d5e21d/abilities/2/ab_all_3040078000_03.js", ImageAssets = { new ImageAsset { Name = "ab_all_3040078000_03", Path = "npc/60d4c46a-f1bd-4d11-b39b-e18835d5e21d/abilities/2/ab_all_3040078000_03.png", }, }, }, AnimationName = "ab_motion", Effects = { new AbilityEffect { Type = AbilityEffect.Types.AbilityEffectType.MultihitDamage, ExtraData = new MultihitDamage { Element = damageElement, HitNumber = 1, HitAllTargets = true, DamageModifier = 2, DamageCap = 470000, }.ToByteString(), }, }, ProcessEffects = (zooey, target, raidActions) => { var random = ThreadSafeRandom.NextDouble(); foreach (var enemy in zooey.Raid.Enemies) { if (enemy.IsAlive() && enemy.PositionInFrontline < 4) { enemy.ApplyStatusEffect( new StatusEffectSnapshot { Id = random <= 1.0 / 3 ? StatusEffectLibrary.StackableDefenseDownNpc : (random <= 2.0 / 3 ? StatusEffectLibrary.StackableAttackDownNpc : StatusEffectLibrary.StackableDebuffResistanceDownNpc), Strength = -10, IsStackable = true, StackingCap = random <= 1.0 / 3 ? -25 : -30, BaseAccuracy = 100, RemainingDurationInSeconds = 180, }, raidActions); } } }, }); }
public static Npc NewInstance() { return(new Npc { Id = Id, Name = "Bahamut", Gender = Gender.Unknown, Attack = 0, MaxHp = 1_500_000_000, Level = 150, Description = string.Empty, Defense = 20, Element = Element.Dark, MaxChargeDiamonds = 3, ModelMetadata = new ModelMetadata { ConstructorName = "mc_enemy_7300293", JsAssetPath = "npc/bahamut/model/enemy_7300293.js", ImageAssets = { new ImageAsset { Name = "enemy_7300293_a", Path = "npc/bahamut/model/enemy_7300293_a.png", }, new ImageAsset { Name = "enemy_7300293_b", Path = "npc/bahamut/model/enemy_7300293_b.png", }, }, DisplayRegistrationPointX = 80, DisplayRegistrationPointY = -120, }, OnHitEffectModelMetadata = new ModelMetadata { ConstructorName = "mc_ehit_7300213_all_effect", JsAssetPath = "npc/bahamut/model/ehit_7300213_all.js", ImageAssets = { new ImageAsset { Name = "ehit_7300213_all", Path = "npc/bahamut/model/ehit_7300213_all.png", }, }, }, OnSetup = (bahamut) => { bahamut.GlobalState.Add("form", TypedValue.FromLong(InitialForm)); bahamut.MaxChargeDiamonds = 3; }, OnActionStart = (bahamut, raidActions) => { }, OnSpecialAttackStart = (bahamut, raidActions) => { if (bahamut.GlobalState["form"].IntegerValue == InitialForm) { Reginleiv(bahamut, raidActions); } else if (bahamut.GlobalState["form"].IntegerValue == FireForm) { if (bahamut.IsInOverdriveMode()) { if (ThreadSafeRandom.NextDouble() < 0.5) { FireIV(bahamut, raidActions); } else { ScarletRain(bahamut, raidActions); } } else { FireIV(bahamut, raidActions); } } else if (bahamut.GlobalState["form"].IntegerValue == WaterForm) { if (bahamut.IsInOverdriveMode()) { if (ThreadSafeRandom.NextDouble() < 0.5) { FreezeIV(bahamut, raidActions); } else { SilverWave(bahamut, raidActions); } } else { FreezeIV(bahamut, raidActions); } } }, OnAttackStart = (bahamut, raidActions) => { if (bahamut.Raid.Turn == 0) { RagnarokFieldII(bahamut, raidActions); bahamut.NoChargeDiamondGainThisTurn = true; return false; } return true; }, OnTurnEnd = (bahamut, raidActions) => { foreach (var enemy in bahamut.Raid.Enemies) { if (enemy.IsAlive() && enemy.PositionInFrontline < 4 && enemy.GetStatusEffects().Any(e => e.Id == RagnarokFieldId)) { enemy.DealRawDamage((long)(enemy.MaxHp * 0.05 / bahamut.Raid.NumParticipants), Element.Null, raidActions); } } if (bahamut.HpPercentage <= 25) { ChangeToFinalForm(bahamut, raidActions); } else if (bahamut.HpPercentage <= 50) { ChangeToDarkForm(bahamut, raidActions); } else if (bahamut.HpPercentage <= 60) { ChangeToWindForm(bahamut, raidActions); } else if (bahamut.HpPercentage <= 70) { ChangeToEarthForm(bahamut, raidActions); } else if (bahamut.HpPercentage <= 80) { ChangeToWaterForm(bahamut, raidActions); } else if (bahamut.HpPercentage <= 90) { ChangeToFireForm(bahamut, raidActions); } }, OnHitEffectDelaysInMs = { 180, 180, 180 }, });