public TimeSpan Next() { long curr = backoffFactor; TimeSpan currMax; try { currMax = minDelay + step.Multiply(curr); // may throw OverflowException if (currMax <= TimeSpan.Zero) { throw new OverflowException(); } } catch (OverflowException) { currMax = maxDelay; } currMax = StandardExtensions.Min(currMax, maxDelay); if (currMax < maxDelay) // keep counting only if we did not alraedy reach maxDelay. { try { curr = checked (curr * 2); } catch (OverflowException) { } // if overflows, stop incrementing and just keep the old value. backoffFactor = curr; // now ExponentialBackoff is thread safe. Not serialized (simultanous calls are not guaranteed to be serialized one by one), but thread safe. } if (minDelay >= currMax) { throw new ArgumentOutOfRangeException(String.Format("minDelay {0}, currMax = {1}", minDelay, currMax)); } return(random.NextTimeSpan(minDelay, currMax)); }
public void Eval(String start, String expect) { EncogProgramContext context = new EncogProgramContext(); StandardExtensions.CreateNumericOperators(context); PrgPopulation pop = new PrgPopulation(context, 1); ICalculateScore score = new ZeroEvalScoreFunction(); TrainEA genetic = new TrainEA(pop, score); genetic.ValidationMode = true; genetic.CODEC = new PrgCODEC(); genetic.AddOperation(0.95, new SubtreeCrossover()); genetic.AddOperation(0.05, new SubtreeMutation(context, 4)); genetic.AddScoreAdjuster(new ComplexityAdjustedScore()); genetic.Rules.AddRewriteRule(new RewriteConstants()); genetic.Rules.AddRewriteRule(new RewriteAlgebraic()); EncogProgram expression = new EncogProgram(context); expression.CompileExpression(start); RenderCommonExpression render = new RenderCommonExpression(); genetic.Rules.Rewrite(expression); Assert.AreEqual(expect, render.Render(expression)); }
public TimeSpan Next(int attempt) { TimeSpan currMax; try { long multiple = checked (1 << attempt); currMax = minDelay + step.Multiply(multiple); // may throw OverflowException if (currMax <= TimeSpan.Zero) { throw new OverflowException(); } } catch (OverflowException) { currMax = maxDelay; } currMax = StandardExtensions.Min(currMax, maxDelay); if (minDelay >= currMax) { throw new ArgumentOutOfRangeException(String.Format("minDelay {0}, currMax = {1}", minDelay, currMax)); } return(random.NextTimeSpan(minDelay, currMax)); }
/// <summary> /// Construct the object. /// </summary> /// <param name="theAnalyst">The analyst.</param> /// <param name="theBackwardWindowSize">The backward window size.</param> /// <param name="theForwardWindowSize">The forward window size.</param> public AnalystProcess(EncogAnalyst theAnalyst, int theBackwardWindowSize, int theForwardWindowSize) { analyst = theAnalyst; backwardWindowSize = theBackwardWindowSize; forwardWindowSize = theForwardWindowSize; StandardExtensions.CreateAll(programContext); }
public void TestDepth() { EncogProgramContext context = new EncogProgramContext(); context.DefineVariable("x"); StandardExtensions.CreateAll(context); PrgGrowGenerator rnd = new PrgGrowGenerator(context, 2); EncogProgram prg = (EncogProgram)rnd.Generate(new EncogRandom()); RenderCommonExpression render = new RenderCommonExpression(); }
public bool MarkAsFresh(GrainId key) { GrainDirectoryCacheEntry result; if (!cache.TryGetValue(key, out result)) { return(false); } TimeSpan newExpirationTimer = StandardExtensions.Min(maxExpirationTimer, result.ExpirationTimer.Multiply(exponentialTimerGrowth)); result.Refresh(newExpirationTimer); return(true); }
private PrgPopulation Create() { EncogProgramContext context = new EncogProgramContext(); context.DefineVariable("x"); StandardExtensions.CreateAll(context); PrgPopulation pop = new PrgPopulation(context, 10); EncogProgram prg1 = new EncogProgram(context); EncogProgram prg2 = new EncogProgram(context); prg1.CompileExpression("x+1"); prg2.CompileExpression("(x+5)/2"); ISpecies defaultSpecies = pop.CreateSpecies(); defaultSpecies.Add(prg1); defaultSpecies.Add(prg2); return(pop); }
/// <summary> /// Create a feed forward network. /// </summary> /// <param name="architecture">The architecture string to use.</param> /// <param name="input">The input count.</param> /// <param name="output">The output count.</param> /// <returns>The feedforward network.</returns> public IMLMethod Create(String architecture, int input, int output) { if (input <= 0) { throw new EncogError("Must have at least one input for EPL."); } if (output <= 0) { throw new EncogError("Must have at least one output for EPL."); } IDictionary <String, String> args = ArchitectureParse.ParseParams(architecture); var holder = new ParamsHolder(args); int populationSize = holder.GetInt( MLMethodFactory.PropertyPopulationSize, false, 1000); String variables = holder.GetString("vars", false, "x"); String funct = holder.GetString("funct", false, null); var context = new EncogProgramContext(); string[] tok = variables.Split(','); foreach (string v in tok) { context.DefineVariable(v); } if (String.Compare("numeric", funct, StringComparison.OrdinalIgnoreCase) == 0) { StandardExtensions.CreateNumericOperators(context); } var pop = new PrgPopulation(context, populationSize); if (context.Functions.Count > 0) { (new RampedHalfAndHalf(context, 2, 6)).Generate(new EncogRandom(), pop); } return(pop); }
private async Task Start() { try { this.log.LogInformation( (int)ErrorCode.MembershipStarting, "MembershipOracle starting on host {HostName} with SiloAddress {SiloAddress} at {StartTime}", this.localSiloDetails.DnsHostName, this.myAddress, LogFormatter.PrintDate(this.siloStartTime)); // Init the membership table. await this.membershipTableProvider.InitializeMembershipTable(true); if (this.clusterMembershipOptions.ExpectedClusterSize > 1) { // randomly delay the startup, so not all silos write to the table at once. // Use random time not larger than MaxJoinAttemptTime, one minute and 0.5sec*ExpectedClusterSize; // Skip waiting if we expect only one member for the cluster. var random = new SafeRandom(); var maxDelay = TimeSpan.FromMilliseconds(500).Multiply(this.clusterMembershipOptions.ExpectedClusterSize); maxDelay = StandardExtensions.Min(maxDelay, StandardExtensions.Min(this.clusterMembershipOptions.MaxJoinAttemptTime, TimeSpan.FromMinutes(1))); var randomDelay = random.NextTimeSpan(maxDelay); await Task.Delay(randomDelay); } var table = await this.RefreshInternal(); LogMissedIAmAlives(table); // read the table and look for my node migration occurrences DetectNodeMigration(table, this.localSiloDetails.DnsHostName); } catch (Exception exception) { this.log.LogError((int)ErrorCode.MembershipFailedToStart, "Membership failed to start: {Exception}", exception); throw; } }
public MembershipTableManager( ILocalSiloDetails localSiloDetails, IOptions <ClusterMembershipOptions> clusterMembershipOptions, IMembershipTable membershipTable, IFatalErrorHandler fatalErrorHandler, IMembershipGossiper gossiper, ILogger <MembershipTableManager> log, IAsyncTimerFactory timerFactory) { this.localSiloDetails = localSiloDetails; this.membershipTableProvider = membershipTable; this.fatalErrorHandler = fatalErrorHandler; this.gossiper = gossiper; this.clusterMembershipOptions = clusterMembershipOptions.Value; this.myAddress = this.localSiloDetails.SiloAddress; this.log = log; var backOffMax = StandardExtensions.Max(EXP_BACKOFF_STEP.Multiply(this.clusterMembershipOptions.ExpectedClusterSize), SiloMessageSender.CONNECTION_RETRY_DELAY.Multiply(2)); this.EXP_BACKOFF_CONTENTION_MAX = backOffMax; this.EXP_BACKOFF_ERROR_MAX = backOffMax; this.snapshot = new MembershipTableSnapshot( this.CreateLocalSiloEntry(this.CurrentStatus), MembershipVersion.MinValue, ImmutableDictionary <SiloAddress, MembershipEntry> .Empty); this.updates = new AsyncEnumerable <MembershipTableSnapshot>( (previous, proposed) => proposed.Version > previous.Version, this.snapshot) { OnPublished = update => Interlocked.Exchange(ref this.snapshot, update) }; this.membershipUpdateTimer = timerFactory.Create( this.clusterMembershipOptions.TableRefreshTimeout, nameof(PeriodicallyRefreshMembershipTable)); }
/// <summary> /// Load all known functions as opcodes. /// </summary> public void LoadAllFunctions() { StandardExtensions.CreateAll(this); }
/// <summary> /// Construct the Encog program and create a default context and variable /// holder. Use all available opcodes. /// </summary> public EncogProgram() : this(new EncogProgramContext(), new EncogProgramVariables()) { StandardExtensions.CreateAll(_context); }
/// <summary> /// Program entry point. /// </summary> /// <param name="app">Holds arguments and other info.</param> public void Execute(IExampleInterface app) { IMLDataSet trainingData = GenerationUtil.GenerateSingleDataRange( (x) => (3 * Math.Pow(x, 2) + (12 * x) + 4) , 0, 100, 1); EncogProgramContext context = new EncogProgramContext(); context.DefineVariable("x"); StandardExtensions.CreateNumericOperators(context); PrgPopulation pop = new PrgPopulation(context, 1000); MultiObjectiveFitness score = new MultiObjectiveFitness(); score.AddObjective(1.0, new TrainingSetScore(trainingData)); TrainEA genetic = new TrainEA(pop, score); genetic.ValidationMode = true; genetic.CODEC = new PrgCODEC(); genetic.AddOperation(0.5, new SubtreeCrossover()); genetic.AddOperation(0.25, new ConstMutation(context, 0.5, 1.0)); genetic.AddOperation(0.25, new SubtreeMutation(context, 4)); genetic.AddScoreAdjuster(new ComplexityAdjustedScore(10, 20, 10, 20.0)); genetic.Rules.AddRewriteRule(new RewriteConstants()); genetic.Rules.AddRewriteRule(new RewriteAlgebraic()); genetic.Speciation = new PrgSpeciation(); (new RampedHalfAndHalf(context, 1, 6)).Generate(new EncogRandom(), pop); genetic.ShouldIgnoreExceptions = false; EncogProgram best = null; genetic.ThreadCount = 1; try { for (int i = 0; i < 1000; i++) { genetic.Iteration(); best = (EncogProgram)genetic.BestGenome; Console.Out.WriteLine(genetic.IterationNumber + ", Error: " + best.Score + ",Best Genome Size:" + best.Size + ",Species Count:" + pop.Species.Count + ",best: " + best.DumpAsCommonExpression()); } //EncogUtility.evaluate(best, trainingData); Console.Out.WriteLine("Final score:" + best.Score + ", effective score:" + best.AdjustedScore); Console.Out.WriteLine(best.DumpAsCommonExpression()); //pop.dumpMembers(Integer.MAX_VALUE); //pop.dumpMembers(10); } catch (Exception t) { Console.Out.WriteLine(t.ToString()); } finally { genetic.FinishTraining(); EncogFramework.Instance.Shutdown(); } }
public async Task TopGameTime([Summary("The specified game.")][Remainder] string name) { try { DateTime startTime = DateTime.Now; EmbedBuilder embedBuilder = new EmbedBuilder() { Title = $"{name} Leaderboard" }; EmbedService.BuildSuccessEmbed(embedBuilder); embedBuilder.Description = ""; ImageSearchResult result = await ImageService.SearchImage($"{name} icon", 1); embedBuilder.ThumbnailUrl = result.Url; using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { SimpleStopWatch watch = new SimpleStopWatch(); List <DiscordGameTime> playerGameTime = DBContext.GameTime.FromSql("SELECT * FROM GameTime WHERE Name = {0} ORDER BY Minutes DESC LIMIT 5", name).AsNoTracking().ToList(); if (playerGameTime.Count == 0) { await ReplyAsync("", embed : EmbedService.MakeFailFeedbackEmbed($"No Gametime found for the game [{name.Bold()}].")); return; } for (int i = 0; i < Math.Min(5, playerGameTime.Count()); i++) { var gameTime = playerGameTime.ElementAt(i); DiscordUser user = DBContext.Users.FromSql("SELECT * FROM Users WHERE Id = {0} LIMIT 1", gameTime.Id.ToString()).AsNoTracking().ToList().SingleOrDefault(); if (user == null) { continue; } string text = StandardExtensions.GetAgeText(DateTime.Now.AddMinutes(-gameTime.Minutes)); embedBuilder.AddField(x => { x.Name = "#" + (i + 1) + " " + user.Username; x.Value = new TimeSpan(0, (int)gameTime.Minutes, 0).ToNiceTime(); }); } var totalGameTime = DBContext.GameTime.FromSql("SELECT * FROM GameTime WHERE Name = {0}", name).AsNoTracking().Sum(x => x.Minutes); TimeSpan totalMinutes = new TimeSpan(0, (int)totalGameTime, 0); //string txt = StandardExtensions.GetAgeText(DateTime.Now.AddMinutes(-totalMinutes)); //TimeSpan time = new TimeSpan(0, totalMinutes, 0); embedBuilder.WithFooter(footer => { footer.Text = $"⏰ {"Generated in:"} {watch.Stop().TotalMilliseconds}ms"; }); embedBuilder.Description = $"{"Total Gametime:".Code()} {totalMinutes.ToNiceTime().ToString()} \n"; } await ReplyAsync("", embed : embedBuilder); } catch (Exception ex) { Console.WriteLine(ex.Message); } }