protected override List <List <double> > GenerateValues() { var rand = new MersenneTwister((uint)Seed); List <List <double> > data = new List <List <double> >(); var p0 = ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, 4.0e5, 6.0e5).ToList(); var A = ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, 0.5, 1.5).ToList(); var T0 = ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, 250.0, 260.0).ToList(); var m_dot = new List <double>(); var m_dot_noise = new List <double>(); data.Add(p0); data.Add(A); data.Add(T0); data.Add(m_dot); data.Add(m_dot_noise); double R = 287.0; double γ = 1.4; var c = Math.Sqrt(γ / R * Math.Pow(2 / (γ + 1), (γ + 1) / (γ - 1))); for (int i = 0; i < p0.Count; i++) { double m_dot_i = p0[i] * A[i] / Math.Sqrt(T0[i]) * c; m_dot.Add(m_dot_i); } var sigma_noise = 0.05 * m_dot.StandardDeviationPop(); m_dot_noise.AddRange(m_dot.Select(md => md + NormalDistributedRandom.NextDouble(rand, 0, sigma_noise))); return(data); }
public static string GenerateUrlCompatibleName(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("The length parameter " + "cannot be below zero!"); } var seed = (uint)(Guid.NewGuid().GetHashCode() + (uint)Int32.MaxValue); var result = new StringBuilder(length); var twister = new MersenneTwister(seed); for (int i = 0; i < length; ++i) { result.Append( (char)twister.Next(Constants.BasicLatinStartSymbolNumber, Constants.BasicLatinEndSymbolNumber)); } for (int i = Constants.BasicLatinExcludedStartSymbolNumber; i <= Constants.BasicLatinExcludedEndSymbolNumber; ++i) { result.Replace( (char)i, (char) twister.Next(Constants.BasicLatinStartDigitSymbolNumber, Constants.BasicLatinEndDigitSymbolNumber)); } return result.ToString(); }
protected override List <List <double> > GenerateValues() { List <List <double> > data = new List <List <double> >(); var rand = new MersenneTwister((uint)Seed); data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, 0, 50).ToList()); // note: range is only [0,50] to prevent NaN values (deviates from gp benchmark paper) data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, -50, 50).ToList()); data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, -50, 50).ToList()); data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, 0, 50).ToList()); // note: range is only [0,50] to prevent NaN values (deviates from gp benchmark paper) data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, 0, 50).ToList()); // note: range is only [0,50] to prevent NaN values (deviates from gp benchmark paper) double x0, x3, x4; List <double> results = new List <double>(); for (int i = 0; i < data[0].Count; i++) { x0 = data[0][i]; x3 = data[3][i]; x4 = data[4][i]; results.Add(6.87 + (11 * Math.Sqrt(7.23 * x0 * x3 * x4))); } data.Add(results); return(data); }
public int getCurrentFrame() { try { MersenneTwister rng = new MersenneTwister(Program.mainform.globalseed); var RAM = SingleThreadRead(MTOffset, 0x8); int Index = BitConverter.ToUInt16(RAM, 0); uint Status = BitConverter.ToUInt32(RAM, 4); var Period = 0; for (int i = 0; i < 624; i++) { rng.Next(); } while (Status.ToString("X8") != rng.CurrentState().ToString() && Period * 624 < FrameMax) { for (int i = 0; i < 624; i++) { rng.Next(); } Period++; } if (Index == 0) { Period++; } return(Math.Min(Period * 624 + Index - 1, FrameMax)); } catch { return(FrameMax); } }
public void MersenneTwisterNextWithMinimumAndMaximumTest() { const int testRange = 100; const uint testCount = 1000U; var random = new MersenneTwister(); for (var counter = 0U; counter < testCount; counter++) { var minimum = random.Next(-testRange, testRange); var maximum = random.Next(-testRange, testRange); Sort(ref minimum, ref maximum); if (minimum == maximum) { maximum++; } for (var c = 0U; c < testCount; c++) { var value = random.Next(minimum, maximum); Assert.IsTrue(minimum <= value); Assert.IsTrue(value < maximum); } } }
public static Int32 Next() { lock (Lock) { return(Random.Next()); } }
public void InitializeRandomWaves1(int nbWaves) { // Aucune vague n'est liée à une autre = toutes les vagues sont indépendantes // frequence = 2 * PI / wavelength // phase = speed * frequence NBWAVES = nbWaves; wave = new WaveOptions[nbWaves]; for (int w = 0; w < nbWaves; w++) { //mRand.Initialize(); float t = mRand.NextFloatPositive(); wave[w] = new WaveOptions(); wave[w].Len = 15f * t * mRand.NextFloatPositive(); wave[w].Amp = wave[w].Len * 0.025f; wave[w].Speed = wave[w].Len * mRand.NextFloatPositive(); wave[w].Angle = 30f * mRand.NextFloat() * Math.Sign(mRand.Next(-2, 2)); wave[w].Dir = new Vector2((float)Math.Cos(MathHelper.ToRadians(wave[w].Angle)), (float)Math.Sin(MathHelper.ToRadians(wave[w].Angle))); wave[w].Freq = 2f * (float)Math.PI / wave[w].Len; wave[w].Phase = wave[w].Speed * wave[w].Freq; System.Diagnostics.Debug.WriteLine("{" + w + "} " + wave[w].ToString()); } }
// Called by the host's player creation code public void Activate(Player p) { Player = p; IsEnabled = true; playerPower = p.PlayerActor.Trait <PowerManager>(); supportPowerMngr = p.PlayerActor.Trait <SupportPowerManager>(); playerResource = p.PlayerActor.Trait <PlayerResources>(); foreach (var building in Info.BuildingQueues) { builders.Add(new BaseBuilder(this, building, p, playerPower, playerResource)); } foreach (var defense in Info.DefenseQueues) { builders.Add(new BaseBuilder(this, defense, p, playerPower, playerResource)); } Random = new MersenneTwister((int)p.PlayerActor.ActorID); // Avoid all AIs trying to rush in the same tick, randomize their initial rush a little. var smallFractionOfRushInterval = Info.RushInterval / 20; rushTicks = Random.Next(Info.RushInterval - smallFractionOfRushInterval, Info.RushInterval + smallFractionOfRushInterval); // Avoid all AIs reevaluating assignments on the same tick, randomize their initial evaluation delay. assignRolesTicks = Random.Next(0, Info.AssignRolesInterval); attackForceTicks = Random.Next(0, Info.AttackForceInterval); minAttackForceDelayTicks = Random.Next(0, Info.MinimumAttackForceDelay); resourceTypeIndices = new BitArray(World.TileSet.TerrainInfo.Length); // Big enough foreach (var t in Map.Rules.Actors["world"].TraitInfos <ResourceTypeInfo>()) { resourceTypeIndices.Set(World.TileSet.GetTerrainIndex(t.TerrainType), true); } }
public IEnumerable <IRenderable> Render(WorldRenderer wr) { if (wr.World.FogObscures(target) && wr.World.FogObscures(source)) { yield break; } if (ticks < info.Duration) { foreach (var zap in zaps) { var offsets = zap.Second; for (var i = 1; i < offsets.Length - 1; i++) { var angle = WAngle.FromDegrees(random.Next(360)); var distortion = random.Next(info.Distortion); var offset = distortion * angle.Cos() * leftVector / (1024 * 1024) + distortion * angle.Sin() * upVector / (1024 * 1024); offsets[i] += offset; } yield return(new ElectricBoltRenderable(offsets, info.ZOffset, info.Width, zap.First)); } } }
protected override List <List <double> > GenerateValues() { List <List <double> > data = new List <List <double> >(); var rand = new MersenneTwister((uint)Seed); data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, -50, 50).ToList()); data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, -50, 50).ToList()); data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, 0, 50).ToList()); // note: range is only [0,50] to prevent NaN values (deviates from gp benchmark paper) data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, -50, 50).ToList()); data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), TestPartitionEnd, -50, 50).ToList()); double x0, x1, x2, x3; List <double> results = new List <double>(); for (int i = 0; i < data[0].Count; i++) { x0 = data[0][i]; x1 = data[1][i]; x2 = data[2][i]; x3 = data[3][i]; results.Add(12.0 - (6.0 * ((Math.Tan(x0) / Math.Exp(x1)) * (Math.Log(x2) - Math.Tan(x3))))); } data.Add(results); return(data); }
public CPos ChooseRandomCell(MersenneTwister rand) { var x = rand.Next(Bounds.Left, Bounds.Right); var y = rand.Next(Bounds.Top, Bounds.Bottom); return(new MPos(x, y).ToCPos(this)); }
protected override List <List <double> > GenerateValues() { List <List <double> > data = new List <List <double> >(); var rand = new MersenneTwister((uint)Seed); for (int i = 0; i < AllowedInputVariables.Count(); i++) { data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), 1024, 0.05, 6.05).ToList()); data[i].AddRange(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), 5000, -0.25, 6.35)); } double x1, x2, x3, x4, x5; List <double> results = new List <double>(); for (int i = 0; i < data[0].Count; i++) { x1 = data[0][i]; x2 = data[1][i]; x3 = data[2][i]; x4 = data[3][i]; x5 = data[4][i]; results.Add(10 / (5 + Math.Pow(x1 - 3, 2) + Math.Pow(x2 - 3, 2) + Math.Pow(x3 - 3, 2) + Math.Pow(x4 - 3, 2) + Math.Pow(x5 - 3, 2))); } data.Add(results); return(data); }
/// <summary> Main mod function. </summary> /// <param name="helper">The helper. </param> public override void Entry(IModHelper helper) { RWeatherIcon = new Rectangle(); WeatherOpt = helper.ReadConfig <WeatherConfig>(); Dice = new MersenneTwister(); DebugOutput = new StringBuilder(); OurMoon = new SDVMoon(WeatherOpt, Dice); OurIcons = new Sprites.Icons(Helper.Content); CropList = new List <Vector2>(); Conditions = new WeatherConditions(OurIcons, Dice, Helper.Translation, Monitor, WeatherOpt); StaminaMngr = new StaminaDrain(WeatherOpt, Helper.Translation, Monitor); SeedsForDialogue = new int[] { Dice.Next(), Dice.Next() }; DescriptionEngine = new Descriptions(Helper.Translation, Dice, WeatherOpt, Monitor); queuedMsg = null; Vector2 snowPos = Vector2.Zero; TicksOutside = 0; TicksTotal = 0; ExpireTime = 0; if (WeatherOpt.Verbose) { Monitor.Log($"Loading climate type: {WeatherOpt.ClimateType} from file", LogLevel.Trace); } string path = Path.Combine("data", "weather", WeatherOpt.ClimateType + ".json"); GameClimate = helper.ReadJsonFile <FerngillClimate>(path); if (GameClimate is null) { this.Monitor.Log($"The required '{path}' file is missing. Try reinstalling the mod to fix that.", LogLevel.Error); this.Monitor.Log("This mod will now disable itself.", LogLevel.Error); this.Disabled = true; } if (!Disabled) { //subscribe to events TimeEvents.AfterDayStarted += HandleNewDay; SaveEvents.BeforeSave += OnEndOfDay; TimeEvents.TimeOfDayChanged += TenMinuteUpdate; MenuEvents.MenuChanged += MenuEvents_MenuChanged; GameEvents.UpdateTick += CheckForChanges; SaveEvents.AfterReturnToTitle += ResetMod; SaveEvents.AfterLoad += SaveEvents_AfterLoad; GraphicsEvents.OnPostRenderGuiEvent += DrawOverMenus; GraphicsEvents.OnPreRenderHudEvent += DrawPreHudObjects; GraphicsEvents.OnPostRenderHudEvent += DrawObjects; LocationEvents.CurrentLocationChanged += LocationEvents_CurrentLocationChanged; ControlEvents.KeyPressed += (sender, e) => this.ReceiveKeyPress(e.KeyPressed, this.WeatherOpt.Keyboard); MenuEvents.MenuClosed += (sender, e) => this.ReceiveMenuClosed(e.PriorMenu); //console commands helper.ConsoleCommands .Add("weather_settommorow", helper.Translation.Get("console-text.desc_tmrweather"), TomorrowWeatherChangeFromConsole) .Add("weather_changeweather", helper.Translation.Get("console-text.desc_setweather"), WeatherChangeFromConsole) .Add("world_solareclipse", "Starts the solar eclipse.", SolarEclipseEvent_CommandFired); } }
public CPos ChooseRandomCell(MersenneTwister rand) { var x = rand.Next(Bounds.Left, Bounds.Right); var y = rand.Next(Bounds.Top, Bounds.Bottom); return(MapToCell(TileShape, new CPos(x, y))); }
protected override List <List <double> > GenerateValues() { List <List <double> > data = new List <List <double> >(); var rand = new MersenneTwister((uint)Seed); for (int i = 0; i < AllowedInputVariables.Count(); i++) { data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), 300, 0.05, 6.05).ToList()); } for (int i = 0; i < AllowedInputVariables.Count(); i++) { data[i].AddRange(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), 1000, -0.25, 6.35)); } double x1, x2; List <double> results = new List <double>(); for (int i = 0; i < data[0].Count; i++) { x1 = data[0][i]; x2 = data[1][i]; results.Add((x1 - 3) * (x2 - 3) + 2 * Math.Sin((x1 - 4) * (x2 - 4))); } data.Add(results); return(data); }
public void generateApple() { MersenneTwister mt = new MersenneTwister(); Apple apple = new Apple(apples.ElementAt(mt.Next(1, 5)), mt.Next(150, 800), 0.5f, (float)Utils.ConvertToRadians(mt.Next(0, 360))); airApple.Add(apple); }
int[] GetRandomPose() { return(new int[] { (int)Mathf.Ceil(rng.Next(0, 90) / shoulderResolution) * shoulderResolution, (int)Mathf.Ceil(rng.Next(30, 300) / elbowResolution) * elbowResolution }); }
private void Advance(BWRng pidrng, MersenneTwister ivrng, List <DreamRadarFrame.Spin> spins) { // first PIDRNG advance = spin spins.Add((DreamRadarFrame.Spin)pidrng.GetNext32BitNumber(8)); pidrng.GetNext64BitNumber(); ivrng.Next(); ivrng.Next(); }
public CPos ChooseRandomEdgeCell(MersenneTwister rand) { var isX = rand.Next(2) == 0; var edge = rand.Next(2) == 0; var x = isX ? rand.Next(Bounds.Left, Bounds.Right) : (edge ? Bounds.Left : Bounds.Right); var y = !isX?rand.Next(Bounds.Top, Bounds.Bottom) : (edge ? Bounds.Top : Bounds.Bottom); return(MapToCell(TileShape, new CPos(x, y))); }
public static T Random <T>(this IEnumerable <T> ts, MersenneTwister r) { var xs = ts as ICollection <T>; if (xs != null) { return(xs.ElementAt(r.Next(xs.Count))); } var ys = ts.ToList(); return(ys[r.Next(ys.Count)]); }
public override IEnumerable <IDataDescriptor> GetDataDescriptors() { List <IDataDescriptor> descriptorList = new List <IDataDescriptor>(); var rand = new MersenneTwister((uint)Seed); descriptorList.Add(new BreimanOne(rand.Next())); descriptorList.Add(new FriedmanOne(rand.Next())); descriptorList.Add(new FriedmanTwo(rand.Next())); descriptorList.Add(new PolyTen(rand.Next())); descriptorList.Add(new SpatialCoevolution(rand.Next())); return(descriptorList); }
public void MoveWeather() { updateRaindropPosition(); TimeSpan timeSpan; if (Game1.currentLocation.IsOutdoors) { for (int index = 0; index < this.rainDrops.Length; ++index) { if (this.rainDrops[index].frame == 0) { ref int local = ref this.rainDrops[index].accumulator; int num3 = local; timeSpan = Game1.currentGameTime.ElapsedGameTime; int milliseconds = timeSpan.Milliseconds; local = num3 + milliseconds; if (this.rainDrops[index].accumulator >= 70) { this.rainDrops[index].position += new Vector2( (float)(index * 8 / this.rainDrops.Length - 16), (float)(32 - index * 8 / this.rainDrops.Length)); this.rainDrops[index].accumulator = 0; if (pRNG.NextDouble() < 0.1) { ++this.rainDrops[index].frame; } if ((double)this.rainDrops[index].position.Y > (double)(Game1.viewport.Height + 64)) { this.rainDrops[index].position.Y = -64f; } } } else { ref int local = ref this.rainDrops[index].accumulator; int num3 = local; timeSpan = Game1.currentGameTime.ElapsedGameTime; int milliseconds = timeSpan.Milliseconds; local = num3 + milliseconds; if (this.rainDrops[index].accumulator > 70) { this.rainDrops[index].frame = (this.rainDrops[index].frame + 1) % 4; this.rainDrops[index].accumulator = 0; if (this.rainDrops[index].frame == 0) { this.rainDrops[index].position = new Vector2( (float)pRNG.Next(Game1.viewport.Width), (float)pRNG.Next(Game1.viewport.Height)); } } }
ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue) { var buildableThings = queue.BuildableItems(); if (!buildableThings.Any()) { return(null); } var unit = buildableThings.ElementAtOrDefault(random.Next(buildableThings.Count())); return(HasAdequateAirUnits(unit) ? unit : null); }
public void CreateWeather() { //set the begin and end time SDVTime stormStart = new SDVTime(1150 + (Dice.Next(0, 230))); stormStart.ClampToTenMinutes(); BeginTime = new SDVTime(stormStart); stormStart.AddTime(Dice.Next(30, 190)); stormStart.ClampToTenMinutes(); ExpirTime = new SDVTime(stormStart); }
public CPos ChooseRandomCell(MersenneTwister rand) { MPos[] cells; do { var u = rand.Next(Bounds.Left, Bounds.Right); var v = rand.Next(Bounds.Top, Bounds.Bottom); cells = Unproject(new PPos(u, v)); } while (!cells.Any()); return(cells.Random(rand).ToCPos(TileShape)); }
static IEnumerable<CPos> RandomWalk(CPos p, MersenneTwister r) { for (;;) { var dx = r.Next(-1, 2); var dy = r.Next(-1, 2); if (dx == 0 && dy == 0) continue; p += new CVec(dx, dy); yield return p; } }
private void DrawContent(DrawingVisual visual, MersenneTwister twister) { // simulate heavy workload (see Tektosyne User's Guide) Thread.Sleep(1000); using (DrawingContext context = visual.RenderOpen()) { for (int i = 0; i < 100; i++) { int width = twister.Next(4, 40); int height = twister.Next(4, 40); int x = twister.Next(_cellWidth - width); int y = twister.Next(_cellHeight - height); Rect rect = new Rect(x, y, width, height); Brush brush = new SolidColorBrush(Color.FromArgb( (byte)twister.Next(255), (byte)twister.Next(255), (byte)twister.Next(255), (byte)twister.Next(255))); Pen pen = new Pen(new SolidColorBrush(Color.FromArgb( (byte)twister.Next(255), (byte)twister.Next(255), (byte)twister.Next(255), (byte)twister.Next(255))), 1); context.DrawRectangle(brush, pen, rect); } } }
public CPos ChooseRandomEdgeCell(MersenneTwister rand) { MPos[] cells; do { var isU = rand.Next(2) == 0; var edge = rand.Next(2) == 0; var u = isU ? rand.Next(Bounds.Left, Bounds.Right) : (edge ? Bounds.Left : Bounds.Right); var v = !isU?rand.Next(Bounds.Top, Bounds.Bottom) : (edge ? Bounds.Top : Bounds.Bottom); cells = Unproject(new PPos(u, v)); } while (!cells.Any()); return(cells.Random(rand).ToCPos(TileShape)); }
private void HandleNewDay(object sender, EventArgs e) { if (CropList == null) { Monitor.Log("CropList is null!"); } if (DebugOutput == null) { Monitor.Log("DebugOutput is null!"); } if (OurMoon == null) { Monitor.Log("OurMoon is null"); } if (Conditions == null) { Monitor.Log("CurrentWeather is null"); } if (StaminaMngr == null) { Monitor.Log("StaminaMngr is null"); } if (GameClimate is null) { Monitor.Log("GameClimate is null"); } if (Dice.NextDouble() < WeatherOpt.EclipseChance && WeatherOpt.EclipseOn && OurMoon.CurrentPhase == MoonPhase.FullMoon && SDate.Now().DaysSinceStart > 2) { IsEclipse = true; Game1.addHUDMessage(new HUDMessage("It looks like a rare solar eclipse will darken the sky all day!")); Conditions.BlockFog = true; } SeedsForDialogue[0] = Dice.Next(); SeedsForDialogue[1] = Dice.Next(); CropList.Clear(); //clear the crop list DebugOutput.Clear(); Conditions.OnNewDay(); UpdateWeatherOnNewDay(); SetTommorowWeather(); OurMoon.HandleMoonAfterWake(Helper.Translation); StaminaMngr.OnNewDay(); TicksOutside = 0; ExpireTime = 0; TicksTotal = 0; }
// Code that runs on entering the state. public override void OnEnter() { MersenneTwister random = new MersenneTwister(); storeResult.Value = random.Next(max.Value); Finish(); }
public static int DrunkardWalk(Unit unit) { MersenneTwister mt = new MersenneTwister(); unit.MakeAMove((CardinalDirection)mt.Next(9)); return 100; }
private void Search6_Timeline() { if (!TTT.HasSeed) { FormUtil.Error("Please Calibrate Timeline"); return; } var timeline = TTT.gettimeline(); int min = Math.Max((int)Frame_min.Value, timeline.Startingframe + 2); int max = (int)TimeSpan.Value * 60 + min; timeline.Maxframe = max; timeline.Generate(ForMainForm: true); int listlength = timeline.TinyLength; // Prepare var rng = new MersenneTwister(Seed.Value); for (int i = 0; i < min; i++) { rng.Next(); } getsetting(rng); Frame.standard = (int)(TargetFrame.Value - min); for (int i = 0; i < listlength; i++) { var tinyframe = timeline.results[i]; if (tinyframe.unhitable) { continue; } if (tinyframe.framemax < min) { continue; } RNGPool.TinySynced = tinyframe.sync == true; // For stationary for (int j = tinyframe.framemin + 2; j <= tinyframe.framemax; j += 2, RNGPool.AddNext(rng), RNGPool.AddNext(rng)) { while (j < min) { j += 2; } RNGPool.tinystatus = tinyframe.tinystate.Clone(); RNGPool.tinystatus.Currentframe = j; RNGResult result = RNGPool.Generate6(); if (!filter.CheckResult(result)) { continue; } Frames.Add(new Frame(result, frame: j, time: j - min)); Frames.Last()._tinystate = new PRNGState(tinyframe.tinystate.Status); if (Frames.Count > MAX_RESULTS_NUM) { return; } } } }
protected override List <List <double> > GenerateValues() { List <List <double> > data = new List <List <double> >(); List <double> oneVariableTestData = SequenceGenerator.GenerateSteps(-0.2m, 4.2m, 0.1m).Select(v => (double)v).ToList(); List <List <double> > testData = new List <List <double> >() { oneVariableTestData, oneVariableTestData }; var combinations = ValueGenerator.GenerateAllCombinationsOfValuesInLists(testData).ToList <IEnumerable <double> >(); var rand = new MersenneTwister((uint)Seed); for (int i = 0; i < AllowedInputVariables.Count(); i++) { data.Add(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), 100, 0.3, 4).ToList()); data[i].AddRange(combinations[i]); } double x1, x2; List <double> results = new List <double>(); for (int i = 0; i < data[0].Count; i++) { x1 = data[0][i]; x2 = data[1][i]; results.Add(Math.Exp(-Math.Pow(x1 - 1, 2)) / (1.2 + Math.Pow(x2 - 2.5, 2))); } data.Add(results); return(data); }
public static void MyClassInitialize(TestContext testContext) { random = new MersenneTwister(); coordinates = new DoubleMatrix(ProblemSize, 2); distances = new DistanceMatrix(ProblemSize, ProblemSize); for (int i = 0; i < ProblemSize; i++) { coordinates[i, 0] = random.Next(ProblemSize * 10); coordinates[i, 1] = random.Next(ProblemSize * 10); } for (int i = 0; i < ProblemSize - 1; i++) { for (int j = i + 1; j < ProblemSize; j++) { distances[i, j] = Math.Round(Math.Sqrt(Math.Pow(coordinates[i, 0] - coordinates[j, 0], 2) + Math.Pow(coordinates[i, 1] - coordinates[j, 1], 2))); distances[j, i] = distances[i, j]; } } tour = new Permutation(PermutationTypes.RelativeUndirected, ProblemSize, random); }
protected override List <List <double> > GenerateValues() { List <List <double> > data = new List <List <double> >(); List <double> evenlySpacedSequence = SequenceGenerator.GenerateSteps(-5, 5, 0.4m).Select(v => (double)v).ToList(); List <List <double> > trainingData = new List <List <double> >() { evenlySpacedSequence, evenlySpacedSequence }; var combinations = ValueGenerator.GenerateAllCombinationsOfValuesInLists(trainingData).ToList(); var rand = new MersenneTwister((uint)Seed); for (int i = 0; i < AllowedInputVariables.Count(); i++) { data.Add(combinations[i].ToList()); data[i].AddRange(ValueGenerator.GenerateUniformDistributedValues(rand.Next(), 1000, -5, 5).ToList()); } double x, y; List <double> results = new List <double>(); for (int i = 0; i < data[0].Count; i++) { x = data[0][i]; y = data[1][i]; results.Add(1 / (1 + Math.Pow(x, -4)) + 1 / (1 + Math.Pow(y, -4))); } data.Add(results); return(data); }
public static void InitTree(ISymbolicExpressionTree tree, MersenneTwister twister, List<string> varNames) { foreach (var node in tree.IterateNodesPostfix()) { if (node is VariableTreeNode) { var varNode = node as VariableTreeNode; varNode.Weight = twister.NextDouble() * 20.0 - 10.0; varNode.VariableName = varNames[twister.Next(varNames.Count)]; } else if (node is ConstantTreeNode) { var constantNode = node as ConstantTreeNode; constantNode.Value = twister.NextDouble() * 20.0 - 10.0; } } }
// Use this for initialization void Start () { rand = new MersenneTwister (); if(player.RoomsTotal == 0) { roomsTotal = rand.Next (NUM_ROOMS_MIN, NUM_ROOMS_MAX); player.RoomsTotal = roomsTotal; labelRoomClear.text = "0 / " + roomsTotal.ToString (); } else { roomsTotal = player.RoomsTotal; roomsCleared = player.RoomsLeft; labelRoomClear.text = roomsCleared.ToString () + " / " + roomsTotal.ToString (); } }
public static void MyClassInitialize(TestContext testContext) { random = new MersenneTwister(); coordinates = new DoubleMatrix(ProblemSize, 2); distances = new DistanceMatrix(ProblemSize, ProblemSize); for (var i = 0; i < ProblemSize; i++) { coordinates[i, 0] = random.Next(ProblemSize * 10); coordinates[i, 1] = random.Next(ProblemSize * 10); } for (var i = 0; i < ProblemSize - 1; i++) { for (var j = i + 1; j < ProblemSize; j++) { distances[i, j] = Math.Round(Math.Sqrt(Math.Pow(coordinates[i, 0] - coordinates[j, 0], 2) + Math.Pow(coordinates[i, 1] - coordinates[j, 1], 2))); distances[j, i] = distances[i, j]; } } probabilities = new DoubleArray(ProblemSize); for (var i = 0; i < ProblemSize; i++) { probabilities[i] = random.NextDouble(); } realizations = new ItemList<BoolArray>(RealizationsSize); for (var i = 0; i < RealizationsSize; i++) { var countOnes = 0; var newRealization = new BoolArray(ProblemSize); while (countOnes < 4) { //only generate realizations with at least 4 cities visited countOnes = 0; for (var j = 0; j < ProblemSize; j++) { newRealization[j] = random.NextDouble() < probabilities[j]; if (newRealization[j]) countOnes++; } } realizations.Add(newRealization); } tour = new Permutation(PermutationTypes.RelativeUndirected, ProblemSize, random); }
public void SubtreeCrossoverDistributionsTest() { int generations = 5; var trees = new List<ISymbolicExpressionTree>(); var grammar = Grammars.CreateArithmeticAndAdfGrammar(); var random = new MersenneTwister(31415); double msPerCrossoverEvent; for (int i = 0; i < POPULATION_SIZE; i++) { trees.Add(ProbabilisticTreeCreator.Create(random, grammar, 100, 10)); for (int j = random.Next(3); j < 3; j++) SubroutineCreater.CreateSubroutine(random, trees[i], 100, 10, 3, 3); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int gCount = 0; gCount < generations; gCount++) { for (int i = 0; i < POPULATION_SIZE; i++) { var par0 = (ISymbolicExpressionTree)trees.SampleRandom(random).Clone(); var par1 = (ISymbolicExpressionTree)trees.SampleRandom(random).Clone(); SubtreeCrossover.Cross(random, par0, par1, 0.9, 100, 10); } } stopwatch.Stop(); foreach (var tree in trees) Util.IsValid(tree); msPerCrossoverEvent = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE / (double)generations; Console.WriteLine("SubtreeCrossover: " + Environment.NewLine + msPerCrossoverEvent + " ms per crossover event (~" + Math.Round(1000.0 / (msPerCrossoverEvent)) + "crossovers / s)" + Environment.NewLine + Util.GetSizeDistributionString(trees, 105, 5) + Environment.NewLine + Util.GetFunctionDistributionString(trees) + Environment.NewLine + Util.GetNumberOfSubtreesDistributionString(trees) + Environment.NewLine + Util.GetTerminalDistributionString(trees) + Environment.NewLine ); //mkommend: commented due to performance issues on the builder //Assert.IsTrue(Math.Round(1000.0 / (msPerCrossoverEvent)) > 2000); // must achieve more than 2000 x-overs/s }
public void SubroutineDuplicaterDistributionsTest() { var trees = new List<ISymbolicExpressionTree>(); var grammar = Grammars.CreateArithmeticAndAdfGrammar(); var random = new MersenneTwister(); for (int i = 0; i < POPULATION_SIZE; i++) { ISymbolicExpressionTree tree = null; do { tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH); for (int j = random.Next(3); j < 3; j++) SubroutineCreater.CreateSubroutine(random, tree, 100, 10, 3, 3); } while (!HasOneAdf(tree)); var success = SubroutineDuplicater.DuplicateSubroutine(random, tree, 3, 3); Assert.IsTrue(success); Util.IsValid(tree); trees.Add(tree); } Console.WriteLine("SubroutineDuplicater: " + Environment.NewLine + Util.GetSizeDistributionString(trees, 105, 5) + Environment.NewLine + Util.GetFunctionDistributionString(trees) + Environment.NewLine + Util.GetNumberOfSubtreesDistributionString(trees) + Environment.NewLine + Util.GetTerminalDistributionString(trees) + Environment.NewLine ); }
private static void CopmareRandomGeneratorsSpeed() { var sw = new Stopwatch(); var maxCount = 10000000; sw.Start(); var r1 = new Random(); for (int i = 0; i < maxCount; i++) { var x = r1.Next(); } sw.Stop(); var time1 = sw.ElapsedMilliseconds; sw.Restart(); var r2 = new MersenneTwister(); for (int i = 0; i < maxCount; i++) { var x = r2.Next(); } sw.Stop(); var time2 = sw.ElapsedMilliseconds; }
public static void MyClassInitialize(TestContext testContext) { random = new MersenneTwister(); symmetricDistances = new DoubleMatrix(ProblemSize, ProblemSize); symmetricWeights = new DoubleMatrix(ProblemSize, ProblemSize); asymmetricDistances = new DoubleMatrix(ProblemSize, ProblemSize); asymmetricWeights = new DoubleMatrix(ProblemSize, ProblemSize); nonZeroDiagonalDistances = new DoubleMatrix(ProblemSize, ProblemSize); nonZeroDiagonalWeights = new DoubleMatrix(ProblemSize, ProblemSize); for (int i = 0; i < ProblemSize - 1; i++) { for (int j = i + 1; j < ProblemSize; j++) { symmetricDistances[i, j] = random.Next(ProblemSize * 100); symmetricDistances[j, i] = symmetricDistances[i, j]; symmetricWeights[i, j] = random.Next(ProblemSize * 100); symmetricWeights[j, i] = symmetricWeights[i, j]; asymmetricDistances[i, j] = random.Next(ProblemSize * 100); asymmetricDistances[j, i] = random.Next(ProblemSize * 100); asymmetricWeights[i, j] = random.Next(ProblemSize * 100); asymmetricWeights[j, i] = random.Next(ProblemSize * 100); nonZeroDiagonalDistances[i, j] = random.Next(ProblemSize * 100); nonZeroDiagonalDistances[j, i] = random.Next(ProblemSize * 100); nonZeroDiagonalWeights[i, j] = random.Next(ProblemSize * 100); nonZeroDiagonalWeights[j, i] = random.Next(ProblemSize * 100); } nonZeroDiagonalDistances[i, i] = random.Next(ProblemSize * 100); nonZeroDiagonalWeights[i, i] = random.Next(ProblemSize * 100); } int index = random.Next(ProblemSize); if (nonZeroDiagonalDistances[index, index] == 0) nonZeroDiagonalDistances[index, index] = random.Next(1, ProblemSize * 100); index = random.Next(ProblemSize); if (nonZeroDiagonalWeights[index, index] == 0) nonZeroDiagonalWeights[index, index] = random.Next(1, ProblemSize * 100); assignment = new Permutation(PermutationTypes.Absolute, ProblemSize, random); }
public NKLandscape() : base() { random = new MersenneTwister(); Parameters.Add(new ValueParameter<BoolMatrix>("GeneInteractions", "Every column gives the participating genes for each fitness component.")); Parameters.Add(new ValueParameter<IntValue>("ProblemSeed", "The seed used for the random number generator.", new IntValue(0))); random.Reset(Seed.Value); Parameters.Add(new ValueParameter<IntValue>("InteractionSeed", "The seed used for the hash function to generate interaction tables.", new IntValue(random.Next()))); Parameters.Add(new ValueParameter<IntValue>("NrOfFitnessComponents", "Number of fitness component functions. (nr of columns in the interaction column)", new IntValue(10))); Parameters.Add(new ValueParameter<IntValue>("NrOfInteractions", "Number of genes interacting with each other. (nr of True values per column in the interaction matrix)", new IntValue(3))); Parameters.Add(new ValueParameter<IntValue>("Q", "Number of allowed fitness values in the (virutal) random table, or zero.", new IntValue(0))); Parameters.Add(new ValueParameter<DoubleValue>("P", "Probability of any entry in the (virtual) random table being zero.", new DoubleValue(0))); Parameters.Add(new ValueParameter<DoubleArray>("Weights", "The weights for the component functions. If shorted, will be repeated.", new DoubleArray(new[] { 1.0 }))); Parameters.Add(new ConstrainedValueParameter<IInteractionInitializer>("InteractionInitializer", "Initialize interactions within the component functions.")); Parameters.Add(new ConstrainedValueParameter<IWeightsInitializer>("WeightsInitializer", "Operator to initialize the weights distribution.")); //allow just the standard NK[P,Q] formulations at the moment WeightsParameter.Hidden = true; InteractionInitializerParameter.Hidden = true; WeightsInitializerParameter.Hidden = true; EncodingParameter.Hidden = true; InitializeInteractionInitializerParameter(); InitializeWeightsInitializerParameter(); InitializeOperators(); InitializeInteractions(); RegisterEventHandlers(); }
/// <summary> /// shows lines on the calibration pattern /// </summary> /// <param name="filename">raw image filename</param> /// <param name="lines">lines to be shown</param> /// <param name="output_filename">filename to save as</param> private static void ShowLines(string filename, List<List<double>> lines, string output_filename) { Bitmap bmp = (Bitmap)Bitmap.FromFile(filename); byte[] img = new byte[bmp.Width * bmp.Height * 3]; BitmapArrayConversions.updatebitmap(bmp, img); MersenneTwister rnd = new MersenneTwister(0); for (int i = 0; i < lines.Count; i++) { int r = 0; int g = 255; int b = 0; r = rnd.Next(255); g = rnd.Next(255); b = rnd.Next(255); List<double> line = lines[i]; double prev_x = 0, prev_y = 0; for (int j = 0; j < line.Count; j += 2) { double x = line[j]; double y = line[j + 1]; if (j > 0) drawing.drawLine(img, bmp.Width, bmp.Height, (int)prev_x, (int)prev_y, (int)x, (int)y, r, g, b, 0, false); prev_x = x; prev_y = y; } } Bitmap output_bmp = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); BitmapArrayConversions.updatebitmap_unsafe(img, output_bmp); if (output_filename.ToLower().EndsWith("jpg")) output_bmp.Save(output_filename, System.Drawing.Imaging.ImageFormat.Jpeg); if (output_filename.ToLower().EndsWith("bmp")) output_bmp.Save(output_filename, System.Drawing.Imaging.ImageFormat.Bmp); }
public CPos ChooseRandomEdgeCell(MersenneTwister rand) { List<MPos> cells; do { var isU = rand.Next(2) == 0; var edge = rand.Next(2) == 0; var u = isU ? rand.Next(Bounds.Left, Bounds.Right) : (edge ? Bounds.Left : Bounds.Right); var v = !isU ? rand.Next(Bounds.Top, Bounds.Bottom) : (edge ? Bounds.Top : Bounds.Bottom); cells = Unproject(new PPos(u, v)); } while (!cells.Any()); return cells.Random(rand).ToCPos(Grid.Type); }
public HSLColor RandomValidColor(MersenneTwister random, IEnumerable<Color> terrainColors, IEnumerable<Color> playerColors) { HSLColor color; Color forbidden; Action<string> ignoreError = _ => { }; do { var h = random.Next(255) / 255f; var s = float2.Lerp(HsvSaturationRange[0], HsvSaturationRange[1], random.NextFloat()); var v = float2.Lerp(HsvValueRange[0], HsvValueRange[1], random.NextFloat()); color = HSLColor.FromHSV(h, s, v); } while (!IsValid(color.RGB, out forbidden, terrainColors, playerColors, ignoreError)); return color; }
public static string RandomString(MersenneTwister oRandom, string pattern) { string ret = ""; //Dichiarazione delle costanti const char LNV = '@'; //Consonante Minuscola const char UNV = '$'; //Consonante Maiuscola const char LV = '!'; //Vocale Minuscola const char UV = '&'; //Vocale Maiuscola const char AL = '*'; //Qualsiasi lettera minuscola const char AU = '-'; //Qualsiasi lettera maiuscola const char I = '#'; //Numero Intero const char OU = '^'; //Una 'o' o una 'u' const char UOU = '>'; //Una 'O' o una 'U' const char AE = '%'; //Una 'a' o una 'e' const char UAE = '_'; //Una 'A' o una 'E' //------------------------------------------------------------------ //Dichiarazione array di caratteri char[] ArrayAlfabeto = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; char[] ArrayConsonanti = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' }; char[] ArrayVocali = { 'a', 'e', 'i', 'o', 'u' }; //------------------------------------------------------------------ foreach (char character in pattern.ToCharArray()) { switch (character) { case LNV: ret += ArrayConsonanti.GetValue(oRandom.Next(20)).ToString().ToLower(); break; case UNV: ret += ArrayConsonanti.GetValue(oRandom.Next(20)).ToString().ToUpper(); break; case LV: ret += ArrayVocali.GetValue(oRandom.Next(4)).ToString().ToLower(); break; case UV: ret += ArrayVocali.GetValue(oRandom.Next(4)).ToString().ToUpper(); break; case AL: ret += ArrayAlfabeto.GetValue(oRandom.Next(25)).ToString().ToLower(); break; case AU: ret += ArrayAlfabeto.GetValue(oRandom.Next(25)).ToString().ToUpper(); break; case I: ret += oRandom.Next(9); break; case OU: ret += ArrayVocali.GetValue(oRandom.Next(3, 4)).ToString().ToLower(); break; case UOU: ret += ArrayVocali.GetValue(oRandom.Next(3, 4)).ToString().ToUpper(); break; case AE: ret += ArrayVocali.GetValue(oRandom.Next(1)).ToString().ToLower(); break; case UAE: ret += ArrayVocali.GetValue(oRandom.Next(1)).ToString().ToUpper(); break; default: ret += character; break; } } return ret; }
public void AllArchitectureAlteringOperatorsDistributionTest() { var trees = new List<ISymbolicExpressionTree>(); var newTrees = new List<ISymbolicExpressionTree>(); var grammar = Grammars.CreateArithmeticAndAdfGrammar(); var random = new MersenneTwister(31415); SymbolicExpressionTreeStringFormatter formatter = new SymbolicExpressionTreeStringFormatter(); IntValue maxTreeSize = new IntValue(MAX_TREE_LENGTH); IntValue maxTreeHeigth = new IntValue(MAX_TREE_DEPTH); IntValue maxDefuns = new IntValue(3); IntValue maxArgs = new IntValue(3); for (int i = 0; i < POPULATION_SIZE; i++) { var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH); Util.IsValid(tree); trees.Add(tree); } Stopwatch stopwatch = new Stopwatch(); int failedEvents = 0; for (int g = 0; g < N_ITERATIONS; g++) { for (int i = 0; i < POPULATION_SIZE; i++) { if (random.NextDouble() < 0.5) { // manipulate stopwatch.Start(); var selectedTree = (ISymbolicExpressionTree)trees.SampleRandom(random).Clone(); var oldTree = (ISymbolicExpressionTree)selectedTree.Clone(); bool success = false; int sw = random.Next(6); switch (sw) { case 0: success = ArgumentCreater.CreateNewArgument(random, selectedTree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); break; case 1: success = ArgumentDeleter.DeleteArgument(random, selectedTree, 3, 3); break; case 2: success = ArgumentDuplicater.DuplicateArgument(random, selectedTree, 3, 3); break; case 3: success = SubroutineCreater.CreateSubroutine(random, selectedTree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); break; case 4: success = SubroutineDuplicater.DuplicateSubroutine(random, selectedTree, 3, 3); break; case 5: success = SubroutineDeleter.DeleteSubroutine(random, selectedTree, 3, 3); break; } stopwatch.Stop(); if (!success) failedEvents++; Util.IsValid(selectedTree); newTrees.Add(selectedTree); } else { stopwatch.Start(); // crossover SymbolicExpressionTree par0 = null; SymbolicExpressionTree par1 = null; do { par0 = (SymbolicExpressionTree)trees.SampleRandom(random).Clone(); par1 = (SymbolicExpressionTree)trees.SampleRandom(random).Clone(); } while (par0.Length > MAX_TREE_LENGTH || par1.Length > MAX_TREE_LENGTH); var newTree = SubtreeCrossover.Cross(random, par0, par1, 0.9, MAX_TREE_LENGTH, MAX_TREE_DEPTH); stopwatch.Stop(); Util.IsValid(newTree); newTrees.Add(newTree); } } trees = new List<ISymbolicExpressionTree>(newTrees); newTrees.Clear(); } var msPerOperation = stopwatch.ElapsedMilliseconds / ((double)POPULATION_SIZE * (double)N_ITERATIONS); Console.WriteLine("AllArchitectureAlteringOperators: " + Environment.NewLine + "Operations / s: ~" + Math.Round(1000.0 / (msPerOperation)) + "operations / s)" + Environment.NewLine + "Failed events: " + failedEvents * 100.0 / (double)(POPULATION_SIZE * N_ITERATIONS / 2.0) + "%" + Environment.NewLine + Util.GetSizeDistributionString(trees, 200, 5) + Environment.NewLine + Util.GetFunctionDistributionString(trees) + Environment.NewLine + Util.GetNumberOfSubtreesDistributionString(trees) + Environment.NewLine + Util.GetTerminalDistributionString(trees) + Environment.NewLine ); Assert.IsTrue(failedEvents * 100.0 / (POPULATION_SIZE * N_ITERATIONS / 2.0) < 75.0); // 25% of architecture operations must succeed //mkommend: commented due to performance issues on the builder // Assert.IsTrue(Math.Round(1000.0 / (msPerOperation)) > 800); // must achieve more than 800 ops per second }
public CPos ChooseRandomCell(MersenneTwister rand) { List<MPos> cells; do { var u = rand.Next(Bounds.Left, Bounds.Right); var v = rand.Next(Bounds.Top, Bounds.Bottom); cells = Unproject(new PPos(u, v)); } while (!cells.Any()); return cells.Random(rand).ToCPos(Grid.Type); }
public CPos ChooseRandomEdgeCell(MersenneTwister rand) { var isX = rand.Next(2) == 0; var edge = rand.Next(2) == 0; var x = isX ? rand.Next(Bounds.Left, Bounds.Right) : (edge ? Bounds.Left : Bounds.Right); var y = !isX ? rand.Next(Bounds.Top, Bounds.Bottom) : (edge ? Bounds.Top : Bounds.Bottom); return new MPos(x, y).ToCPos(this); }
/*--- Gold Effect Methods ---*/ #region Gold Effects Functions private void activateEffect() { string itemId = ""; goldEffectActive = true; MersenneTwister random = new MersenneTwister(); int index = random.Next(1, 5); if (!firstCatch) { Debug.Log(TAG + " first catch was " + firstCatch); firstCatch = !firstCatch; Debug.Log(TAG + " first catch is now " + firstCatch); if (effectTimer == 0) effectTimer = 5; switch (index) { case 1: //AndyUtils.LogDebug(TAG, "Index " + index + ": Frenzy"); animGold.gameObject.SetActive(true); animGold.Play("Frenzy"); // The delegate is used here to return to the previously // playing clip after the "hit" animation is done playing. animGold.animationCompleteDelegate = AnimFinishedDelegate; break; case 2: //AndyUtils.LogDebug(TAG, "Index " + index + ": Super Frenzy"); animGold.gameObject.SetActive(true); animGold.Play("Super Frenzy"); // The delegate is used here to return to the previously // playing clip after the "hit" animation is done playing. animGold.animationCompleteDelegate = AnimFinishedDelegate; break; case 3: //AndyUtils.LogDebug(TAG, "Index " + index + ": Double Points"); animGold.gameObject.SetActive(true); animGold.Play("Double"); // The delegate is used here to return to the previously // playing clip after the "hit" animation is done playing. animGold.animationCompleteDelegate = AnimFinishedDelegate; break; case 4: //AndyUtils.LogDebug(TAG, "Index " + index + ": Repellent"); animGold.gameObject.SetActive(true); animGold.Play("Repellent"); // The delegate is used here to return to the previously // playing clip after the "hit" animation is done playing. animGold.animationCompleteDelegate = AnimFinishedDelegate; break; } } // set the item id for the store invetory retrival switch (index) { case 1: // Frenzy //AndyUtils.LogDebug(TAG,"Current Effect Before:" + CURRENT_EFFECT); CURRENT_EFFECT = GOLD_EFFECTS.FRENZY; //AndyUtils.LogDebug(TAG,"Current Effect After:" + CURRENT_EFFECT); itemId = AndysApplesAssets.FRENZY_GOOD.ItemId; break; case 2: // Super Frenzy //AndyUtils.LogDebug(TAG,"Current Effect Before:" + CURRENT_EFFECT); CURRENT_EFFECT = GOLD_EFFECTS.SUPERFRENZY; //AndyUtils.LogDebug(TAG,"Current Effect After:" + CURRENT_EFFECT); itemId = AndysApplesAssets.SUPER_GOOD.ItemId; break; case 3: // Double Points //AndyUtils.LogDebug(TAG,"Current Effect Before:" + CURRENT_EFFECT); CURRENT_EFFECT = GOLD_EFFECTS.DOUBLE; //AndyUtils.LogDebug(TAG,"Current Effect After:" + CURRENT_EFFECT); itemId = AndysApplesAssets.DOUBLE_GOOD.ItemId; break; case 4: // Repellent //AndyUtils.LogDebug(TAG,"Current Effect Before:" + CURRENT_EFFECT); CURRENT_EFFECT = GOLD_EFFECTS.REPEL; //AndyUtils.LogDebug(TAG,"Current Effect After:" + CURRENT_EFFECT); itemId = AndysApplesAssets.REPELLENT_GOOD.ItemId; break; } //AndyUtils.LogDebug(TAG,"now adding to achievements"); achievementTracker.AddProgressToAchievement("Gold Standard", 1.0f); GE_INDEX = index; //AndyUtils.LogDebug(TAG,"now switching on/ Gold effect"); switch (CURRENT_EFFECT) { case GOLD_EFFECTS.FRENZY: achievementTracker.AddProgressToAchievement("Frenzy Fanatic", 1.0f); achievementTracker.AddProgressToAchievement("Fred's Frenzy Bonanaza", 1.0f); if (StoreInventory.GetGoodUpgradeLevel(itemId) < 6) effectTimer += StoreInventory.GetGoodUpgradeLevel(itemId); else effectTimer += 5; break; case GOLD_EFFECTS.SUPERFRENZY: achievementTracker.AddProgressToAchievement("Raining Combos", 1.0f); achievementTracker.AddProgressToAchievement("Super Frenzy Wizard", 1.0f); incrementSuperFrenzyAchievements(); if (StoreInventory.GetGoodUpgradeLevel(itemId) < 6) effectTimer += StoreInventory.GetGoodUpgradeLevel(itemId); else effectTimer += 5; break; case GOLD_EFFECTS.DOUBLE: achievementTracker.AddProgressToAchievement("Twice The Charm", 1.0f); achievementTracker.AddProgressToAchievement("2X Mastery", 1.0f); if (StoreInventory.GetGoodUpgradeLevel(itemId) < 6) effectTimer += StoreInventory.GetGoodUpgradeLevel(itemId); else effectTimer += 5; break; case GOLD_EFFECTS.REPEL: achievementTracker.AddProgressToAchievement("Honor System", 1.0f); achievementTracker.AddProgressToAchievement("No No to Rottens", 1.0f); if (StoreInventory.GetGoodUpgradeLevel(itemId) < 6) effectTimer += StoreInventory.GetGoodUpgradeLevel(itemId); else effectTimer += 5; break; default: break; } //AndyUtils.LogDebug(TAG,"Effect timer length for Gold Effect " + CURRENT_EFFECT + " is " + effectTimer + " seconds."); effectTimerCounter = effectTimer; Invoke("decrementEffectTimer", 1.0f); Invoke("deactivateEffect", (float)effectTimer); }
public CPos ChooseRandomCell(MersenneTwister rand) { var x = rand.Next(Bounds.Left, Bounds.Right); var y = rand.Next(Bounds.Top, Bounds.Bottom); return new MPos(x, y).ToCPos(this); }
public static int Next(int seed, int minInclusive, int maxInclusive) { MersenneTwister mt = new MersenneTwister(seed); return minInclusive + mt.Next((maxInclusive + 1) - minInclusive); }
public static void Main(string[] args) { bool showHelp = false; int width = 500; int height = 500; var options = new OptionSet() { { "?|help", "show this message and exit", v => showHelp = v != null }, { "w|width=", "set level width", v => width = v != null ? int.Parse(v) : width }, { "h|height=", "set level height", v => height = v != null ? int.Parse(v) : height }, }; List<string> extras; try { extras = options.Parse(args); } catch (OptionException e) { Console.Write("{0}: ", GetExecutableName()); Console.WriteLine(e.Message); Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName()); return; } if (extras.Count < 0 || extras.Count > 1 || showHelp == true) { Console.WriteLine("Usage: {0} [OPTIONS]+ [output_map]", GetExecutableName()); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); return; } var outputPath = extras.Count > 0 ? extras[0] : "space.map"; var templates = LoadEntities(); int cx = width / 2; int cy = height / 2; // ReSharper disable UnusedVariable var radius = (int)(Math.Min(width, height) / 2.0); // ReSharper restore UnusedVariable var range = Math.Min(width, height) / 2.5; var rng = new MersenneTwister(); var noise = PerlinNoise.Generate( width, height, 0.0325f, 1.0f, 0.5f, 16, rng); var physics = new bool[width,height]; var vision = new bool[width,height]; var entities = new List<Entity>(); for (int x = 8; x < width - 8; x++) { for (int y = 8; y < height - 8; y++) { var distance = GetDistance(cx, cy, x, y); if (distance > range && rng.Next(100) > 2) { continue; } var magic = noise[x, y]; if (magic >= 200) { } else if (magic >= 180) { if (rng.Next(100) >= 60 && (x % 2) == 0 && (y % 2) == 0) { var template = templates .Where(t => t.Category == "asteroid") .OrderBy(t => rng.Next()) .FirstOrDefault(); if (template != null && template.CanPlaceWithPhysics(x, y, physics, width, height) == true) { var entity = new Entity(x, y, template); int speed = rng.Next(100); if (speed < 60) { entity.AnimationTime = 0; } else if (speed < 70) { entity.AnimationTime = 100; } else if (speed < 80) { entity.AnimationTime = 200; } else if (speed < 85) { entity.AnimationTime = 250; } else if (speed < 90) { entity.AnimationTime = 350; } else if (speed < 95) { entity.AnimationTime = 400; } else { entity.AnimationTime = 450; } template.BlockPhysics(x, y, physics); entities.Add(entity); } } } else if (magic >= 100) { } else if (magic >= 15) { } else { if (rng.Next(100) >= 80) { var template = templates .Where(t => t.Category == "nebula") .OrderBy(t => rng.Next()) .FirstOrDefault(); if (template != null && template.CanPlaceWithVision(x, y, vision, width, height) == true) { var entity = new Entity(x, y, template) { AnimationTime = 50 }; template.BlockVision(x, y, vision); entities.Add(entity); } } } } } var tiles = new Level.Tile[width,height]; foreach (var entity in entities) { for (int rx = 0; rx < entity.Template.Width; rx++) { for (int ry = 0; ry < entity.Template.Height; ry++) { if (entity.Template.Physics[rx, ry] > 0) { tiles[entity.X + rx, entity.Y + ry].Physics = entity.Template.Physics[rx, ry]; } if (entity.Template.Vision[rx, ry] > 0) { tiles[entity.X + rx, entity.Y + ry].Vision = entity.Template.Vision[rx, ry]; } } } } var floors = new List<Map.BlobReference> { new Map.BlobReference() { Path = "f_default.blo,default.cfs" }, }; //floors.Add(new Map.BlobReference() { Path = "f_colors.blo,color3.cfs" }); using (var output = File.Create(outputPath)) { var header = new Map.Header { Version = 9, Width = width, Height = height, EntityCount = entities.Count, LightColorWhite = 0xFFFFFF00u, LightColorRed = 0x0000FF00u, LightColorGreen = 0x00FF0000u, LightColorBlue = 0xFF000000u, PhysicsLow = new short[32], PhysicsHigh = new short[32], }; header.PhysicsHigh[0] = 0; header.PhysicsHigh[1] = 1024; header.PhysicsHigh[2] = 1024; header.PhysicsHigh[3] = 1024; header.PhysicsHigh[4] = 1024; header.PhysicsHigh[5] = 1024; header.PhysicsHigh[6] = 16; header.PhysicsHigh[7] = 16; header.PhysicsHigh[8] = 16; header.PhysicsHigh[9] = 16; header.PhysicsHigh[10] = 16; header.PhysicsHigh[11] = 32; header.PhysicsHigh[12] = 32; header.PhysicsHigh[13] = 32; header.PhysicsHigh[14] = 32; header.PhysicsHigh[15] = 32; header.PhysicsHigh[16] = 64; header.PhysicsHigh[17] = 64; header.PhysicsHigh[18] = 64; header.PhysicsHigh[19] = 64; header.PhysicsHigh[20] = 64; header.PhysicsHigh[21] = 128; header.PhysicsHigh[22] = 128; header.PhysicsHigh[23] = 128; header.PhysicsHigh[24] = 128; header.PhysicsHigh[25] = 128; header.PhysicsHigh[26] = 1024; header.PhysicsHigh[27] = 1024; header.PhysicsHigh[29] = 1024; header.PhysicsHigh[28] = 1024; header.PhysicsHigh[30] = 1024; header.PhysicsHigh[31] = 1024; output.WriteStructure(header); for (int i = 0; i < 8192; i++) { if (i < 16) { output.WriteValueU8((byte)i); } else { output.WriteValueU8(0); } } for (int i = 0; i < 2048; i++) { if (i < floors.Count) { output.WriteStructure(floors[i]); } else { output.Seek(64, SeekOrigin.Current); } } var buffer = new byte[width * height * 4]; for (int y = 0, offset = 0; y < height; y++) { for (int x = 0; x < width; x++, offset += 4) { buffer[offset + 0] = tiles[x, y].BitsA; buffer[offset + 1] = 0; buffer[offset + 2] = tiles[x, y].BitsC; buffer[offset + 3] = tiles[x, y].BitsB; } } using (var rle = new MemoryStream()) { rle.WriteRLE(buffer, 4, width * height, false); rle.Position = 0; output.WriteValueS32((int)rle.Length); output.WriteFromStream(rle, rle.Length); } foreach (var source in entities) { var entity = new Level.Entity { X = (short)((source.X - source.Template.OffsetX) * 16), Y = (short)((source.Y - source.Template.OffsetY) * 16), AnimationTime = source.AnimationTime, }; output.WriteStructure(entity); var reference = new Map.BlobReference { Path = string.Format("{0},{1}", source.Template.BloName, source.Template.CfsName), }; output.WriteStructure(reference); } } }
private void btnReseed_Click(object sender, EventArgs e) { int min = (int)nudMin.Value, max = (int)nudMax.Value; if (!(min == max || (min == 0 && max == 0))) { lbNotSorted.Items.Clear(); MersenneTwister mt = new MersenneTwister(); for (int i = 0; i < 1000; i++) { lbNotSorted.Items.Add(mt.Next(min, max)); } } }
// Called by the host's player creation code public void Activate(Player p) { Player = p; enabled = true; playerPower = p.PlayerActor.Trait<PowerManager>(); supportPowerMngr = p.PlayerActor.Trait<SupportPowerManager>(); playerResource = p.PlayerActor.Trait<PlayerResources>(); foreach (var building in Info.BuildingQueues) builders.Add(new BaseBuilder(this, building, p, playerPower, playerResource)); foreach (var defense in Info.DefenseQueues) builders.Add(new BaseBuilder(this, defense, p, playerPower, playerResource)); Random = new MersenneTwister((int)p.PlayerActor.ActorID); // Avoid all AIs trying to rush in the same tick, randomize their initial rush a little. var smallFractionOfRushInterval = Info.RushInterval / 20; rushTicks = Random.Next(Info.RushInterval - smallFractionOfRushInterval, Info.RushInterval + smallFractionOfRushInterval); // Avoid all AIs reevaluating assignments on the same tick, randomize their initial evaluation delay. assignRolesTicks = Random.Next(0, Info.AssignRolesInterval); attackForceTicks = Random.Next(0, Info.AttackForceInterval); minAttackForceDelayTicks = Random.Next(0, Info.MinimumAttackForceDelay); resourceTypeIndices = new BitArray(World.TileSet.TerrainInfo.Length); // Big enough foreach (var t in Map.Rules.Actors["world"].TraitInfos<ResourceTypeInfo>()) resourceTypeIndices.Set(World.TileSet.GetTerrainIndex(t.TerrainType), true); }
private void Form1_Load(object sender, EventArgs e) { MersenneTwister mt = new MersenneTwister(); for (int i = 0; i < 1000; i++) { lbNotSorted.Items.Add(mt.Next(0, 4000)); } comboAlgorithms.Items.Add("Quick Sort"); comboAlgorithms.Items.Add("Merge Sort"); comboAlgorithms.Items.Add("Heap Sort"); comboAlgorithms.Items.Add("Bubble Sort"); comboAlgorithms.SelectedIndex = 0; }
private void GenerateNewRandom() { var rnd = new MersenneTwister(); _currentRandom = rnd.Next(MinRandom, MaxRandom); }
public CPos ChooseRandomCell(MersenneTwister rand) { var x = rand.Next(Bounds.Left, Bounds.Right); var y = rand.Next(Bounds.Top, Bounds.Bottom); return MapToCell(TileShape, new CPos(x, y)); }
protected override void Run(CancellationToken cancellationToken) { // Set up the algorithm if (SetSeedRandomly) Seed = new System.Random().Next(); var rand = new MersenneTwister((uint)Seed); // Set up the results display var iterations = new IntValue(0); Results.Add(new Result("Iterations", iterations)); var table = new DataTable("Qualities"); table.Rows.Add(new DataRow("R² (train)")); table.Rows.Add(new DataRow("R² (test)")); Results.Add(new Result("Qualities", table)); var curLoss = new DoubleValue(); var curTestLoss = new DoubleValue(); Results.Add(new Result("R² (train)", curLoss)); Results.Add(new Result("R² (test)", curTestLoss)); var runCollection = new RunCollection(); if (StoreRuns) Results.Add(new Result("Runs", runCollection)); // init var problemData = Problem.ProblemData; var targetVarName = problemData.TargetVariable; var activeVariables = problemData.AllowedInputVariables.Concat(new string[] { problemData.TargetVariable }); var modifiableDataset = new ModifiableDataset( activeVariables, activeVariables.Select(v => problemData.Dataset.GetDoubleValues(v).ToList())); var trainingRows = problemData.TrainingIndices; var testRows = problemData.TestIndices; var yPred = new double[trainingRows.Count()]; var yPredTest = new double[testRows.Count()]; var y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray(); var curY = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray(); var yTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToArray(); var curYTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToArray(); var nu = Nu; var mVars = (int)Math.Ceiling(M * problemData.AllowedInputVariables.Count()); var rRows = (int)Math.Ceiling(R * problemData.TrainingIndices.Count()); var alg = RegressionAlgorithm; List<IRegressionModel> models = new List<IRegressionModel>(); try { // Loop until iteration limit reached or canceled. for (int i = 0; i < Iterations; i++) { cancellationToken.ThrowIfCancellationRequested(); modifiableDataset.RemoveVariable(targetVarName); modifiableDataset.AddVariable(targetVarName, curY.Concat(curYTest)); SampleTrainingData(rand, modifiableDataset, rRows, problemData.Dataset, curY, problemData.TargetVariable, problemData.TrainingIndices); // all training indices from the original problem data are allowed var modifiableProblemData = new RegressionProblemData(modifiableDataset, problemData.AllowedInputVariables.SampleRandomWithoutRepetition(rand, mVars), problemData.TargetVariable); modifiableProblemData.TrainingPartition.Start = 0; modifiableProblemData.TrainingPartition.End = rRows; modifiableProblemData.TestPartition.Start = problemData.TestPartition.Start; modifiableProblemData.TestPartition.End = problemData.TestPartition.End; if (!TrySetProblemData(alg, modifiableProblemData)) throw new NotSupportedException("The algorithm cannot be used with GBM."); IRegressionModel model; IRun run; // try to find a model. The algorithm might fail to produce a model. In this case we just retry until the iterations are exhausted if (TryExecute(alg, rand.Next(), RegressionAlgorithmResult, out model, out run)) { int row = 0; // update predictions for training and test // update new targets (in the case of squared error loss we simply use negative residuals) foreach (var pred in model.GetEstimatedValues(problemData.Dataset, trainingRows)) { yPred[row] = yPred[row] + nu * pred; curY[row] = y[row] - yPred[row]; row++; } row = 0; foreach (var pred in model.GetEstimatedValues(problemData.Dataset, testRows)) { yPredTest[row] = yPredTest[row] + nu * pred; curYTest[row] = yTest[row] - yPredTest[row]; row++; } // determine quality OnlineCalculatorError error; var trainR = OnlinePearsonsRCalculator.Calculate(yPred, y, out error); var testR = OnlinePearsonsRCalculator.Calculate(yPredTest, yTest, out error); // iteration results curLoss.Value = error == OnlineCalculatorError.None ? trainR * trainR : 0.0; curTestLoss.Value = error == OnlineCalculatorError.None ? testR * testR : 0.0; models.Add(model); } if (StoreRuns) runCollection.Add(run); table.Rows["R² (train)"].Values.Add(curLoss.Value); table.Rows["R² (test)"].Values.Add(curTestLoss.Value); iterations.Value = i + 1; } // produce solution if (CreateSolution) { // when all our models are symbolic models we can easily combine them to a single model if (models.All(m => m is ISymbolicRegressionModel)) { Results.Add(new Result("Solution", CreateSymbolicSolution(models, Nu, (IRegressionProblemData)problemData.Clone()))); } // just produce an ensemble solution for now (TODO: correct scaling or linear regression for ensemble model weights) var ensembleSolution = CreateEnsembleSolution(models, (IRegressionProblemData)problemData.Clone()); Results.Add(new Result("EnsembleSolution", ensembleSolution)); } } finally { // reset everything alg.Prepare(true); } }