public TownGenerator(int MaxXSearchArea, int MaxZSearchArea) { this._towns = new List<Town> (); this._mt = new MersenneTwister ((uint)DateTime.Now.Ticks); this._maxXSearchArea = MaxXSearchArea; this._maxZSearchArea = MaxZSearchArea; }
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 static int DrunkardWalk(Unit unit) { MersenneTwister mt = new MersenneTwister(); unit.MakeAMove((CardinalDirection)mt.Next(9)); return 100; }
public void ArgumentCreaterDistributionsTest() { var trees = new List<ISymbolicExpressionTree>(); var grammar = Grammars.CreateArithmeticAndAdfGrammar(); var random = new MersenneTwister(31415); int failedOps = 0; for (int i = 0; i < POPULATION_SIZE; i++) { ISymbolicExpressionTree tree; do { tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH); SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); } while (!TreeHasAdfWithParameter(tree, 3)); var success = ArgumentCreater.CreateNewArgument(random, tree, 60000, 100, 3, 3); if (!success) failedOps++; Util.IsValid(tree); trees.Add(tree); } // difficult to make sure that create argument operations succeed because trees are macro-expanded can potentially become very big // => just test if only a small proportion fails Assert.IsTrue(failedOps < POPULATION_SIZE * 0.05); // only 5% may fail Console.WriteLine("ArgumentCreator: " + Environment.NewLine + "Failed operations: " + failedOps * 100.0 / POPULATION_SIZE + " %" + Environment.NewLine + Util.GetSizeDistributionString(trees, 200, 20) + Environment.NewLine + Util.GetFunctionDistributionString(trees) + Environment.NewLine + Util.GetNumberOfSubtreesDistributionString(trees) + Environment.NewLine + Util.GetTerminalDistributionString(trees) + Environment.NewLine ); }
public static string GetIVs(uint seed, int initialFrame, int maxFrame) { string ivs = ""; var rng = new MersenneTwister(seed); rng.Nextuint(); rng.Nextuint(); for (int n = 1; n < initialFrame; n++) { rng.Nextuint(); } int rngCalls = maxFrame - initialFrame; for (int n = 0; n < rngCalls; n++) { uint result = rng.Nextuint(); ivs += GetIV(result); if (n != rngCalls - 1) { ivs += ", "; } } return ivs; }
public void ProbabilisticTreeCreaterDistributionsTest() { var randomTrees = new List<ISymbolicExpressionTree>(); var grammar = Grammars.CreateSimpleArithmeticGrammar(); var random = new MersenneTwister(31415); var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < POPULATION_SIZE; i++) { randomTrees.Add(ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH)); } stopwatch.Stop(); int count = 0; int depth = 0; foreach (var tree in randomTrees) { Util.IsValid(tree); count += tree.Length; depth += tree.Depth; } double msPerRandomTreeCreation = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE; Console.WriteLine("ProbabilisticTreeCreator: " + Environment.NewLine + msPerRandomTreeCreation + " ms per random tree (~" + Math.Round(1000.0 / (msPerRandomTreeCreation)) + "random trees / s)" + Environment.NewLine + Util.GetSizeDistributionString(randomTrees, 105, 5) + Environment.NewLine + Util.GetFunctionDistributionString(randomTrees) + Environment.NewLine + Util.GetNumberOfSubtreesDistributionString(randomTrees) + Environment.NewLine + Util.GetTerminalDistributionString(randomTrees) + Environment.NewLine + "Average tree depth: " + depth / POPULATION_SIZE + Environment.NewLine + "Average tree length: " + count / POPULATION_SIZE + Environment.NewLine + "Total nodes created: " + count + Environment.NewLine ); //mkommend: commented due to performance issues on the builder // Assert.IsTrue(Math.Round(1000.0 / (msPerRandomTreeCreation)) > 250); // must achieve more than 250 random trees / s }
public static MersenneTwister Create() { var random = new Random(); var seed = (uint) (random.Next(int.MaxValue) + (uint) random.Next(int.MaxValue)); var twiseter = new MersenneTwister(seed); return twiseter; }
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(); }
public static string RandomString(string pattern, uint seed) { MersenneTwister oRandom = null; if (seed == 0) oRandom = new MersenneTwister(); else oRandom = new MersenneTwister(seed); return RandomString(oRandom, pattern); }
// Use this for initialization void Start () { rand = new MersenneTwister (); spawnedMobs = new List<GameObject> (); // set local private player object to the singleton player. goPlayer = GameObject.FindWithTag ("Player").GetComponent<Player>(); }
public void RandomEnumerableProducesRangesWithUniformDistributions() { var randomSource = new MersenneTwister(); const double trials = 100000; var zeroFrequency = Enumerable.Range(0, 10).ToDictionary(x => x, x => 0); var fiveFrequency = Enumerable.Range(0, 10).ToDictionary(x => x, x => 0); var nineFrequency = Enumerable.Range(0, 10).ToDictionary(x => x, x => 0); for (var count = 0; count < trials; count++ ) { var result = Lospi.Utils.Statistics.RandomEnumerable.Range(0, 10, randomSource); zeroFrequency[result[0]]++; fiveFrequency[result[5]]++; nineFrequency[result[9]]++; } for (var i = 0; i < 10; i++) { Assert.That(zeroFrequency[i], Is.EqualTo(trials / 10D).Within(10).Percent); Assert.That(fiveFrequency[i], Is.EqualTo(trials / 10D).Within(10).Percent); Assert.That(nineFrequency[i], Is.EqualTo(trials / 10D).Within(10).Percent); } }
// Code that runs on entering the state. public override void OnEnter() { MersenneTwister random = new MersenneTwister(); storeResult.Value = random.Next(max.Value); Finish(); }
public GbmState(IRegressionProblemData problemData, ILossFunction lossFunction, uint randSeed, int maxSize, double r, double m, double nu) { // default settings for MaxSize, Nu and R this.maxSize = maxSize; this.nu = nu; this.r = r; this.m = m; this.randSeed = randSeed; random = new MersenneTwister(randSeed); this.problemData = problemData; this.trainingRows = problemData.TrainingIndices.ToArray(); this.testRows = problemData.TestIndices.ToArray(); this.lossFunction = lossFunction; int nRows = trainingRows.Length; y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, trainingRows).ToArray(); treeBuilder = new RegressionTreeBuilder(problemData, random); activeIdx = Enumerable.Range(0, nRows).ToArray(); var zeros = Enumerable.Repeat(0.0, nRows).ToArray(); double f0 = lossFunction.LineSearch(y, zeros, activeIdx, 0, nRows - 1); // initial constant value (mean for squared errors) pred = Enumerable.Repeat(f0, nRows).ToArray(); predTest = Enumerable.Repeat(f0, testRows.Length).ToArray(); pseudoRes = new double[nRows]; models = new List<IRegressionModel>(); weights = new List<double>(); // add constant model models.Add(new ConstantModel(f0, problemData.TargetVariable)); weights.Add(1.0); }
private static RandomForestRegressionSolution GridSearch(IRegressionProblemData problemData, out RFParameter bestParameters, int seed = 3141519) { double rmsError, outOfBagRmsError, avgRelError, outOfBagAvgRelError; var random = new MersenneTwister(); bestParameters = RandomForestUtil.GridSearch(problemData, randomForestParameterRanges, seed, maximumDegreeOfParallelism); var model = RandomForestModel.CreateRegressionModel(problemData, problemData.TrainingIndices, bestParameters.N, bestParameters.R, bestParameters.M, seed, out rmsError, out outOfBagRmsError, out avgRelError, out outOfBagAvgRelError); return (RandomForestRegressionSolution)model.CreateRegressionSolution(problemData); }
public Randomizer(string oldRomPath_, string fullSeed) { oldRomPath = oldRomPath_; newRomPath = "smb3rr_" + fullSeed + ".nes"; SeparateFullSeed(fullSeed); // prngSeed and levelFlags are initialized here mt = new MersenneTwister(prngSeed); }
public void SampleKnownValues() { var mt = new MersenneTwister(0); Assert.AreEqual(mt.NextDouble(), 0.5488135023042560); Assert.AreEqual(mt.NextDouble(), 0.5928446163889021); Assert.AreEqual(mt.NextDouble(), 0.7151893649715930); Assert.AreEqual(mt.NextDouble(), 0.8442657440900803); }
public void SampleKnownValues() { var mt = new MersenneTwister(0); Assert.AreEqual(mt.NextDouble(), 0.5488135024320365); Assert.AreEqual(mt.NextDouble(), 0.5928446165269344); Assert.AreEqual(mt.NextDouble(), 0.7151893651381110); Assert.AreEqual(mt.NextDouble(), 0.8442657442866512); }
public HSLColor MakeValid(Color askedColor, MersenneTwister random, IEnumerable<Color> terrainColors, IEnumerable<Color> playerColors, Action<string> onError) { Color forbiddenColor; if (IsValid(askedColor, out forbiddenColor, terrainColors, playerColors, onError)) return new HSLColor(askedColor); // Vector between the 2 colors var vector = new double[] { askedColor.R - forbiddenColor.R, askedColor.G - forbiddenColor.G, askedColor.B - forbiddenColor.B }; // Reduce vector by it's biggest value (more calculations, but more accuracy too) var vectorMax = vector.Max(vv => Math.Abs(vv)); if (vectorMax == 0) vectorMax = 1; // Avoid division by 0 vector[0] /= vectorMax; vector[1] /= vectorMax; vector[2] /= vectorMax; // Color weights var rmean = (double)(askedColor.R + forbiddenColor.R) / 2; var weightVector = new[] { 2.0 + rmean / 256, 4.0, 2.0 + (255 - rmean) / 256, }; var attempt = 1; var allForbidden = terrainColors.Concat(playerColors); HSLColor color; do { // If we reached the limit (The ii >= 255 prevents too much calculations) if (attempt >= 255) { color = RandomValidColor(random, terrainColors, playerColors); break; } // Apply vector to forbidden color var r = (forbiddenColor.R + (int)(vector[0] * weightVector[0] * attempt)).Clamp(0, 255); var g = (forbiddenColor.G + (int)(vector[1] * weightVector[1] * attempt)).Clamp(0, 255); var b = (forbiddenColor.B + (int)(vector[2] * weightVector[2] * attempt)).Clamp(0, 255); // Get the alternative color attempt color = new HSLColor(Color.FromArgb(r, g, b)); attempt++; } while (!IsValid(color.RGB, allForbidden, out forbiddenColor)); return color; }
protected SampleSelecter() { if (rand == null) { uint seed = (uint)Math.Abs(DateTime.Now.Ticks);//TODO test edge cases on seed value rand = new MersenneTwister(seed); } this.Count = 0; }
public void ProbabilisticTreeCreatorSpecificTreeSizesTest() { var grammar = Grammars.CreateSimpleArithmeticGrammar(); var random = new MersenneTwister(31415); for (int targetTreeSize = 3; targetTreeSize <= 100; targetTreeSize++) { var tree = ProbabilisticTreeCreator.CreateExpressionTree(random, grammar, targetTreeSize, ((int)Math.Log(targetTreeSize, 2)) + 2); Assert.AreEqual(targetTreeSize, tree.Length); } }
public override void Main() { DateTime start = DateTime.UtcNow; QuadraticAssignmentProblem qap; if (vars.Contains("qap")) qap = vars.qap; else { var provider = new DreznerQAPInstanceProvider(); var instance = provider.GetDataDescriptors().Single(x => x.Name == "dre56"); var data = provider.LoadData(instance); qap = new QuadraticAssignmentProblem(); qap.Load(data); vars.qap = qap; } const uint seed = 0; const int popSize = 100; const int generations = 1000; const double mutationRate = 0.05; var random = new MersenneTwister(seed); var population = new Permutation[popSize]; var qualities = new double[popSize]; var nextGen = new Permutation[popSize]; var nextQual = new double[popSize]; var qualityChart = new DataTable("Quality Chart"); var qualityRow = new DataRow("Best Quality"); qualityChart.Rows.Add(qualityRow); vars.qualityChart = qualityChart; for (int i = 0; i < popSize; i++) { population[i] = new Permutation(PermutationTypes.Absolute, qap.Weights.Rows, random); qualities[i] = QAPEvaluator.Apply(population[i], qap.Weights, qap.Distances); } var bestQuality = qualities.Min(); var bestQualityGeneration = 0; for (int g = 0; g < generations; g++) { var parents = population.SampleProportional(random, 2 * popSize, qualities, windowing: true, inverseProportional: true).ToArray(); for (int i = 0; i < popSize; i++) { nextGen[i] = PartiallyMatchedCrossover.Apply(random, parents[i * 2], parents[i * 2 + 1]); if (random.NextDouble() < mutationRate) Swap2Manipulator.Apply(random, nextGen[i]); nextQual[i] = QAPEvaluator.Apply(nextGen[i], qap.Weights, qap.Distances); if (nextQual[i] < bestQuality) { bestQuality = nextQual[i]; bestQualityGeneration = g; } } qualityRow.Values.Add(bestQuality); Array.Copy(nextGen, population, popSize); Array.Copy(nextQual, qualities, popSize); } vars.elapsed = new TimeSpanValue(DateTime.UtcNow - start); vars.bestQuality = bestQuality; vars.bestQualityFoundAt = bestQualityGeneration; }
public void SampleTest() { var normal = new Normal(0.0, 1.0); var rnd = new MersenneTwister(); var ms = new MetropolisSampler<double>(0.2, normal.Density, x => Normal.Sample(rnd, x, 0.1), 10); ms.RandomSource = rnd; double sample = ms.Sample(); }
public void VarianceTest() { var rnd = new MersenneTwister(); double [] data = Enumerable.Range(1, 10000000).AsParallel().Select(i => Normal.Sample(rnd, 4.5, 2.0)).ToArray(); double actual = Math.Round(ParallelVariance.Variance2(data), 3, MidpointRounding.AwayFromZero); double expected = Math.Round(Statistics.Variance(data), 3, MidpointRounding.AwayFromZero); Assert.AreEqual(expected, actual); }
public Randomizer(string oldRomPath_, List<TreeViewModel> levelTree) { mt = new MersenneTwister(); oldRomPath = oldRomPath_; prngSeed = mt.Seed; levelFlags = ExtractLevelFlags(levelTree); bool longSeed = !((levelTree[0].IsChecked == true) && (levelTree[1].IsChecked == true) && (levelTree[2].IsChecked == true)); newRomPath = "smb3rr_" + GenerateFullSeed(longSeed) + ".nes"; }
public Theater(TileSet tileset) { this.tileset = tileset; var allocated = false; var type = tileset.EnableDepth ? SheetType.DualIndexed : SheetType.Indexed; Func<Sheet> allocate = () => { if (allocated) throw new SheetOverflowException("Terrain sheet overflow. Try increasing the tileset SheetSize parameter."); allocated = true; return new Sheet(type, new Size(tileset.SheetSize, tileset.SheetSize)); }; sheetBuilder = new SheetBuilder(type, allocate); random = new MersenneTwister(); var frameCache = new FrameCache(Game.ModData.SpriteLoaders); foreach (var t in tileset.Templates) { var variants = new List<Sprite[]>(); foreach (var i in t.Value.Images) { var allFrames = frameCache[i]; var frameCount = tileset.EnableDepth ? allFrames.Length / 2 : allFrames.Length; var indices = t.Value.Frames != null ? t.Value.Frames : Enumerable.Range(0, frameCount); variants.Add(indices.Select(j => { var f = allFrames[j]; var s = sheetBuilder.Allocate(f.Size, f.Offset); Util.FastCopyIntoChannel(s, 0, f.Data); if (tileset.EnableDepth) Util.FastCopyIntoChannel(s, 1, allFrames[j + frameCount].Data); return s; }).ToArray()); } var allSprites = variants.SelectMany(s => s); // Ignore the offsets baked into R8 sprites if (tileset.IgnoreTileSpriteOffsets) allSprites = allSprites.Select(s => new Sprite(s.Sheet, s.Bounds, float2.Zero, s.Channel, s.BlendMode)); templates.Add(t.Value.Id, new TheaterTemplate(allSprites.ToArray(), variants.First().Count(), t.Value.Images.Length)); } // 1x1px transparent tile missingTile = sheetBuilder.Add(new byte[1], new Size(1, 1)); Sheet.ReleaseBuffer(); }
public static Dataset CreateRandomDataset(MersenneTwister twister, int rows, int columns) { double[,] data = new double[rows, columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { data[i, j] = twister.NextDouble() * 2.0 - 1.0; } } IEnumerable<string> variableNames = new string[] { "y" }.Concat(Enumerable.Range(0, columns - 1).Select(x => "x" + x.ToString())); Dataset ds = new Dataset(variableNames, data); return ds; }
public void MetropolisConstructor() { var normal = new Normal(0.0, 1.0); var rnd = new MersenneTwister(); var ms = new MetropolisSampler<double>(0.2, normal.Density, x => Normal.Sample(rnd, x, 0.1), 10); Assert.IsNotNull(ms.RandomSource); ms.RandomSource = rnd; Assert.IsNotNull(ms.RandomSource); }
/// <summary> /// Initializes a new instance of the <see cref="MTRandom"/> class. /// </summary> /// <param name="phrase">Phrase (seed string).</param> public MTRandom(string phrase) { char[] values = phrase.ToCharArray(); System.Int32[] keys = new System.Int32[values.Length]; for (int i = 0; i < values.Length; i++) { // Get the integral value of the character. keys[i] = System.Convert.ToInt32(values[i]); } _rand = new MersenneTwister(keys); }
public static ISymbolicExpressionTree[] CreateRandomTrees(MersenneTwister twister, Dataset dataset, ISymbolicExpressionGrammar grammar, int popSize, int minSize, int maxSize, int maxFunctionDefinitions, int maxFunctionArguments) { foreach (Variable variableSymbol in grammar.Symbols.OfType<Variable>()) { variableSymbol.VariableNames = dataset.VariableNames.Skip(1); } ISymbolicExpressionTree[] randomTrees = new ISymbolicExpressionTree[popSize]; for (int i = 0; i < randomTrees.Length; i++) { randomTrees[i] = ProbabilisticTreeCreator.Create(twister, grammar, maxSize, 10); } return randomTrees; }
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; } } }
internal static int ReturnRndRainAmtInLevel(MersenneTwister dice, RainLevels rl) { return((int)(Math.Round(RainCategories[rl].RandomInFullRange(dice), 0))); }
public static CPos ChooseRandomCell(this World w, MersenneTwister r) { return(new CPos( r.Next(w.Map.Bounds.Left, w.Map.Bounds.Right), r.Next(w.Map.Bounds.Top, w.Map.Bounds.Bottom))); }
internal static void ProcessHazardousCropWeather(WeatherConditions curr, int timeOfDay, MersenneTwister Dice) { //frost works at night, heatwave works during the day if (timeOfDay == 1700) { if (curr.HasWeather(CurrentWeather.Heatwave) || curr.HasWeather(CurrentWeather.Sandstorm)) { ClimatesOfFerngill.Logger.Log("Beginning Heatwave code"); ExpireTime = 2000; Farm f = Game1.getFarm(); int count = 0, maxCrops = (int)Math.Floor(SDVUtilities.CropCountInFarm(f) * ClimatesOfFerngill.WeatherOpt.DeadCropPercentage); foreach (KeyValuePair <Vector2, TerrainFeature> tf in f.terrainFeatures.Pairs) { if (count >= maxCrops) { break; } if (tf.Value is HoeDirt dirt && dirt.crop != null) { if (Dice.NextDouble() <= ClimatesOfFerngill.WeatherOpt.CropResistance) { if (ClimatesOfFerngill.WeatherOpt.Verbose) { ClimatesOfFerngill.Logger.Log($"Dewatering crop at {tf.Key}. Crop is {dirt.crop.indexOfHarvest}"); } CropList.Add(tf.Key); dirt.state.Value = HoeDirt.dry; count++; } } } if (CropList.Count > 0) { if (ClimatesOfFerngill.WeatherOpt.AllowCropDeath) { if (curr.HasWeather(CurrentWeather.Heatwave) && !curr.HasWeather(CurrentWeather.Sandstorm)) { SDVUtilities.ShowMessage(ClimatesOfFerngill.Translator.Get("hud-text.desc_heatwave_kill", new { crops = count }), 3); } if (curr.HasWeather(CurrentWeather.Sandstorm)) { SDVUtilities.ShowMessage(ClimatesOfFerngill.Translator.Get("hud-text.desc_sandstorm_kill", new { crops = count }), 3); } } else { if (curr.HasWeather(CurrentWeather.Heatwave) && !curr.HasWeather(CurrentWeather.Sandstorm)) { SDVUtilities.ShowMessage(ClimatesOfFerngill.Translator.Get("hud-text.desc_heatwave_dry", new { crops = count }), 3); } if (curr.HasWeather(CurrentWeather.Sandstorm)) { SDVUtilities.ShowMessage(ClimatesOfFerngill.Translator.Get("hud-text.desc_sandstorm_dry", new { crops = count }), 3); } } } else { SDVUtilities.ShowMessage(ClimatesOfFerngill.Translator.Get("hud-text.desc_heatwave"), 3); } } } if (Game1.timeOfDay == ExpireTime && ClimatesOfFerngill.WeatherOpt.AllowCropDeath) { ClimatesOfFerngill.Logger.Log("Beginning Crop Death code"); //if it's still de watered - kill it. Farm f = Game1.getFarm(); bool cDead = false; foreach (Vector2 v in CropList) { HoeDirt hd = (HoeDirt)f.terrainFeatures[v]; if (hd.state.Value == HoeDirt.dry) { if (ClimatesOfFerngill.WeatherOpt.Verbose) { ClimatesOfFerngill.Logger.Log($"Killing crop at {v}. Crop is {hd.crop.indexOfHarvest}"); } hd.crop.dead.Value = true; cDead = true; } } CropList.Clear(); //clear the list if (cDead) { SDVUtilities.ShowMessage(ClimatesOfFerngill.Translator.Get("hud-text.desc_heatwave_cropdeath"), 3); } } }
void Initialize() { _playerInfoProps = new Props(); string strDir = _creationParams.Get("StrategyDir"); _playerInfoProps.Set("StrategyDir", strDir); string propsFile = Path.Combine(strDir, "props.xml"); Props props = XmlSerializerExt.Deserialize <Props>(propsFile); int rngSeed = int.Parse(_creationParams.GetDefault("RngSeed", "0")); if (rngSeed == 0) { rngSeed = (int)DateTime.Now.Ticks; } _checkBlinds = bool.Parse(_creationParams.GetDefault("CheckBlinds", "true")); string amountCompareMethodText = _creationParams.GetDefault("AmountSearchMethod", "Equal"); if (amountCompareMethodText == "Equal") { _amountSearchMethod = AmountSearchMethod.Equal; } else if (amountCompareMethodText == "Closest") { _amountSearchMethod = AmountSearchMethod.Closest; } else { throw new ApplicationException(string.Format("Unknown amount compare method {0}", amountCompareMethodText)); } _relProbabIgnoreLevel = double.Parse(_creationParams.GetDefault("RelProbabIgnoreLevel", "0.0"), CultureInfo.InvariantCulture); _playerInfoProps.Set("RelProbabIgnoreLevel", _relProbabIgnoreLevel.ToString()); // Use MersenneTwister because it is under our control on all platforms and // is probably better than System.Random. Random underlyingRng = new MersenneTwister(rngSeed); _moveSelector = new DiscreteProbabilityRng(underlyingRng); _playerInfoProps.Set("RngSeed", rngSeed.ToString()); _deckDescr = XmlSerializerExt.Deserialize <DeckDescriptor>(props.Get("DeckDescriptor")); _chanceAbsrtractions = new IChanceAbstraction[0]; // Create chance abstractions for (int pos = 0; ; pos++) { string caPropName = String.Format("ChanceAbstraction-{0}", pos); string relFileName = props.Get(caPropName); if (string.IsNullOrEmpty(relFileName)) { break; } Array.Resize(ref _chanceAbsrtractions, _chanceAbsrtractions.Length + 1); string absFileName = Path.Combine(strDir, relFileName); _chanceAbsrtractions[pos] = ChanceAbstractionHelper.CreateFromPropsFile(absFileName); _playerInfoProps.Set(caPropName + ".Name", _chanceAbsrtractions[pos].Name); } Dictionary <string, int> fileToPos = new Dictionary <string, int>(); _strategies = new StrategyTree[0]; _strIndexes = new UFTreeChildrenIndex[0]; // Load strategies, reuse if file is the same for (int pos = 0; ; pos++) { string strPropName = String.Format("Strategy-{0}", pos); string relFileName = props.Get(strPropName); if (string.IsNullOrEmpty(relFileName)) { break; } Array.Resize(ref _strategies, _strategies.Length + 1); Array.Resize(ref _strIndexes, _strIndexes.Length + 1); string absFileName = Path.Combine(strDir, relFileName); int existingPos; if (fileToPos.TryGetValue(absFileName, out existingPos)) { _strategies[pos] = _strategies[existingPos]; _strIndexes[pos] = _strIndexes[existingPos]; } else { fileToPos.Add(absFileName, pos); _strategies[pos] = StrategyTree.ReadFDA <StrategyTree>(absFileName); _strIndexes[pos] = new UFTreeChildrenIndex(_strategies[pos], Path.Combine(strDir, "strategy-idx.dat"), false); } _playerInfoProps.Set(strPropName + ".Version", _strategies[pos].Version.ToString()); } // Read blinds for (int strPos = 0; strPos < _strategies.Length; ++strPos) { StringBuilder sb = new StringBuilder(); for (int playerPos = 0; playerPos < _strategies.Length; ++playerPos) { StrategyTreeNode stNode = new StrategyTreeNode(); _strategies[strPos].GetNode(playerPos + 1, &stNode); sb.AppendFormat("{0:0.000000 }", stNode.Amount); } _playerInfoProps.Set("Blinds." + strPos.ToString(), sb.ToString()); } }
public NsmObjectMutator() { _randomGenerator = MersenneTwister.Instance; }
// Sampled a N-sample probability density function in the range [-1024..1024, -1024..1024] // 1 sample produces a rectangular probability // 2 samples produces a triangular probability // ... // N samples approximates a true Gaussian public static WVec FromPDF(MersenneTwister r, int samples) { return(new WVec(WDist.FromPDF(r, samples), WDist.FromPDF(r, samples), WDist.Zero)); }
public static T RandomOrDefault <T>(this IEnumerable <T> ts, MersenneTwister r) { return(Random(ts, r, false)); }
public HSLColor MakeValid(Color askedColor, MersenneTwister random, IEnumerable <Color> terrainColors, IEnumerable <Color> playerColors, Action <string> onError) { Color forbiddenColor; if (IsValid(askedColor, out forbiddenColor, terrainColors, playerColors, onError)) { return(new HSLColor(askedColor)); } // Vector between the 2 colors var vector = new double[] { askedColor.R - forbiddenColor.R, askedColor.G - forbiddenColor.G, askedColor.B - forbiddenColor.B }; // Reduce vector by it's biggest value (more calculations, but more accuracy too) var vectorMax = vector.Max(vv => Math.Abs(vv)); if (vectorMax == 0) { vectorMax = 1; // Avoid division by 0 } vector[0] /= vectorMax; vector[1] /= vectorMax; vector[2] /= vectorMax; // Color weights var rmean = (double)(askedColor.R + forbiddenColor.R) / 2; var weightVector = new[] { 2.0 + rmean / 256, 4.0, 2.0 + (255 - rmean) / 256, }; var attempt = 1; var allForbidden = terrainColors.Concat(playerColors); HSLColor color; do { // If we reached the limit (The ii >= 255 prevents too much calculations) if (attempt >= 255) { color = RandomValidColor(random, terrainColors, playerColors); break; } // Apply vector to forbidden color var r = (forbiddenColor.R + (int)(vector[0] * weightVector[0] * attempt)).Clamp(0, 255); var g = (forbiddenColor.G + (int)(vector[1] * weightVector[1] * attempt)).Clamp(0, 255); var b = (forbiddenColor.B + (int)(vector[2] * weightVector[2] * attempt)).Clamp(0, 255); // Get the alternative color attempt color = new HSLColor(Color.FromArgb(r, g, b)); attempt++; } while (!IsValid(color.RGB, allForbidden, out forbiddenColor)); return(color); }
/// <summary> /// 计算期权现值 /// </summary> /// <param name="option">期权</param> /// <param name="markets">市场</param> /// <returns>计算结果</returns> public override double[] CalcPvs(IOption option, IMarketCondition[] markets) { if (AnalyticalOptionPricerUtil.isForwardFuturesOption(option.UnderlyingProductType)) { //market = market.UpdateCondition(new UpdateMktConditionPack<Dictionary<string, IYieldCurve>>(m => m.DividendCurves, new Dictionary<string, IYieldCurve> { { "", market.DiscountCurve.Value} })); markets = markets.Select(x => x.UpdateCondition(new UpdateMktConditionPack <Dictionary <string, IYieldCurve> >(m => m.DividendCurves, new Dictionary <string, IYieldCurve> { { "", x.DiscountCurve.Value } })) ).ToArray(); } var stochasticProcesses = CreateStochasticProcess1Ds(option, markets); var nProcess = stochasticProcesses.Length; var partitioner = Partitioner.Create(0, NumSimulations, NumSimulations / ParallelDegrees + 1); var partitionerPvs = Enumerable.Range(0, nProcess).Select(x => new List <double>()).ToArray(); var parallelOption = new ParallelOptions() { MaxDegreeOfParallelism = ParallelDegrees }; var size = option.ObservationDates.Length * 2 + 3; List <double>[] result = null; if (MonteCarloCollectPath) { result = new List <double> [NumSimulations + 1]; } Parallel.ForEach(partitioner, parallelOption, (range, loopState) => { var pvs = Enumerable.Range(0, nProcess).Select(x => new List <double>()).ToArray(); var random = new MersenneTwister(); for (var n = range.Item1; n < range.Item2; ++n) { var paths = PathGenerator.GeneratePath(stochasticProcesses, markets.Select(x => x.SpotPrices.Value.Values.First()).ToArray(), markets.Select(x => x.ValuationDate.Value).ToArray(), option.ObservationDates, option.Calendar, option.DayCount, random); for (var i = 0; i < nProcess; ++i) { pvs[i].Add( option.GetPayoff(paths[i]).Sum(cf => cf.PaymentAmount * markets[i].DiscountCurve.Value.GetDf(markets[i].ValuationDate.Value, cf.PaymentDate)) ); //pvs[i].Add(option.GetPayoff(paths[i]).Sum(cf => cf.PaymentAmount * market.DiscountCurve.Value.GetDf(market.ValuationDate.Value, cf.PaymentDate))); } //antithetic path for (var i = 0; i < nProcess; ++i) { pvs[i].Add(option.GetPayoff(paths[i + nProcess]).Sum(cf => cf.PaymentAmount * markets[i].DiscountCurve.Value.GetDf(markets[i].ValuationDate.Value, cf.PaymentDate))); //pvs[i].Add(option.GetPayoff(paths[i + nProcess]).Sum(cf => cf.PaymentAmount * market.DiscountCurve.Value.GetDf(market.ValuationDate.Value, cf.PaymentDate))); } if (MonteCarloCollectPath) { var originalPathPrices = from e in paths[0].ToList() orderby e.Key select e.Value; //original path price evolution //result[n].AddRange(prices.ToList()); result[n] = originalPathPrices.ToList(); //pv result[n].Add(pvs[0].First()); var antiPathPrices = from e in paths[1].ToList() orderby e.Key select e.Value; //antipath price evolution result[n].AddRange(antiPathPrices); //pv result[n].Add(pvs[0].Last()); //expected pv result[n].Add(pvs[0].Average()); } } lock (partitionerPvs) { for (var i = 0; i < nProcess; ++i) { partitionerPvs[i].Add(pvs[i].Average()); } } // }); if (MonteCarloCollectPath) { result[NumSimulations] = Enumerable.Repeat(0.0, 2 * (option.ObservationDates.Length + 1)).ToList(); result[NumSimulations].Add(partitionerPvs[0].Average()); var resultStr = result.Select(digits => string.Join(",", digits)).ToArray(); var folder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var filename = folder + "/MonteCarlo.csv"; File.WriteAllLines(filename, resultStr); } //return partitionerPvs[0].Average(); return(partitionerPvs.Select(x => x.Average()).ToArray()); }
public void StaticSamplesConsistent() { Assert.That(MersenneTwister.Doubles(1000, 1), Is.EqualTo(new MersenneTwister(1).NextDoubles(1000)).Within(1e-12).AsCollection); }
private void GenerateNewRandom() { var rnd = new MersenneTwister(); _currentRandom = rnd.Next(MinRandom, MaxRandom); }
public SP_UCTTreeNodeCreator(double constant, double const_D, MersenneTwister rng) { rnd = rng; this.const_C = constant; this.const_D = const_D; }
/// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { RWeatherIcon = new Rectangle(); WeatherOpt = helper.ReadConfig <WeatherConfig>(); Logger = Monitor; Translator = Helper.Translation; Reflection = Helper.Reflection; MPHandler = Helper.Multiplayer; Dice = new MersenneTwister(); OurIcons = new Sprites.Icons(Helper.Content); WeatherProcessing.Init(); Conditions = new WeatherConditions(); DescriptionEngine = new Descriptions(WeatherOpt, Helper.Translation); queuedMsg = null; SummitRebornLoaded = false; if (WeatherOpt.Verbose) { Monitor.Log($"Loading climate type: {WeatherOpt.ClimateType} from file", LogLevel.Trace); } var path = Path.Combine("assets", "climates", WeatherOpt.ClimateType + ".json"); GameClimate = helper.Data.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) { return; } var harmony = HarmonyInstance.Create("koihimenakamura.climatesofferngill"); harmony.PatchAll(Assembly.GetExecutingAssembly()); ConsoleCommands.Init(); MethodInfo GameLocationDAAFL = AccessTools.Method(typeof(GameLocation), "drawAboveAlwaysFrontLayer"); HarmonyMethod DAAFLTranspiler = new HarmonyMethod(AccessTools.Method(typeof(GameLocationPatches), "DAAFLTranspiler")); Monitor.Log($"Patching {GameLocationDAAFL} with Transpiler: {DAAFLTranspiler}", LogLevel.Trace);; harmony.Patch(GameLocationDAAFL, transpiler: DAAFLTranspiler); MethodInfo GameDrawW = AccessTools.Method(typeof(Game1), "drawWeather"); HarmonyMethod DrawWeatherPrefix = new HarmonyMethod(AccessTools.Method(typeof(Game1Patches), "DrawWeatherPrefix")); Monitor.Log($"Patching {GameDrawW} with Prefix: {DrawWeatherPrefix}", LogLevel.Trace);; harmony.Patch(GameDrawW, prefix: DrawWeatherPrefix); Type t = AccessTools.TypeByName("StardewModdingAPI.Framework.SGame"); MethodInfo SGameDrawImpl = AccessTools.Method(t, "DrawImpl"); HarmonyMethod DrawTrans = new HarmonyMethod(AccessTools.Method(typeof(SGamePatches), "DrawImplTranspiler")); Monitor.Log($"Patching {SGameDrawImpl} with Transpiler: {DrawTrans}", LogLevel.Trace); harmony.Patch(SGameDrawImpl, transpiler: DrawTrans); t = AccessTools.TypeByName("StardewValley.WeatherDebris"); var DebrisConstructor = AccessTools.Constructor(t, new[] { typeof(Vector2), typeof(int), typeof(float), typeof(float), typeof(float) }); HarmonyMethod CtorPatch = new HarmonyMethod(AccessTools.Method(typeof(WeatherDebrisPatches), "CtorPostfix")); Monitor.Log($"Patching {DebrisConstructor} with Postfix: {CtorPatch}", LogLevel.Trace); harmony.Patch(DebrisConstructor, postfix: CtorPatch); MethodInfo DebrisDraw = AccessTools.Method(typeof(WeatherDebris), "draw"); HarmonyMethod DebrisPatch = new HarmonyMethod(AccessTools.Method(typeof(WeatherDebrisPatches), "DrawPrefix")); Monitor.Log($"Patching {DebrisDraw} with Prefix: {DebrisDraw}", LogLevel.Trace); harmony.Patch(DebrisDraw, prefix: DebrisPatch); MethodInfo DebrisUpdate = AccessTools.Method(typeof(WeatherDebris), "update", new[] { typeof(bool) }); HarmonyMethod DebrisUpdatePatch = new HarmonyMethod(AccessTools.Method(typeof(WeatherDebrisPatches), "UpdatePrefix")); Monitor.Log($"Patching {DebrisUpdate} with Prefix: {DebrisUpdatePatch}", LogLevel.Trace); harmony.Patch(DebrisUpdate, prefix: DebrisUpdatePatch); //INSERT DNT CHECKS HERE var modManifest = Helper.ModRegistry.Get("knakamura.dynamicnighttime"); if (modManifest != null) { if (modManifest.Manifest.Version.IsOlderThan("1.2.11")) { Monitor.Log("WARNING: Overcast weather may not work correctly unless you are running Dynamic Night Time 1.2.11 or later", LogLevel.Alert); } } else { //Normal Climates patch goes here. MethodInfo UpdateGameClock = helper.Reflection.GetMethod(SDVUtilities.GetSDVType("Game1"), "UpdateGameClock").MethodInfo; MethodInfo postfixClock = helper.Reflection.GetMethod(typeof(Patches.GameClockPatch), "Postfix").MethodInfo; Monitor.Log($"Postfixing {UpdateGameClock} with {postfixClock}", LogLevel.Trace); harmony.Patch(UpdateGameClock, null, new HarmonyMethod(postfixClock)); } SanityCheckConfigOptions(); //subscribe to events var events = helper.Events; events.GameLoop.DayStarted += OnDayStarted; events.GameLoop.Saving += OnSaving; events.GameLoop.TimeChanged += OnTimeChanged; events.Display.MenuChanged += OnMenuChanged; events.GameLoop.UpdateTicked += OnUpdateTicked; events.GameLoop.GameLaunched += OnGameLaunched; events.GameLoop.OneSecondUpdateTicked += OnOneSecondUpdateTicked; events.GameLoop.ReturnedToTitle += OnReturnedToTitle; events.GameLoop.SaveLoaded += OnSaveLoaded; events.Display.RenderingHud += OnRenderingHud; events.Display.RenderedHud += OnRenderedHud; events.Input.ButtonPressed += OnButtonPressed; events.Multiplayer.ModMessageReceived += OnModMessageRecieved; // events.GameLoop.UpdateTicking += GameLoop_UpdateTicking; //console commands helper.ConsoleCommands .Add("world_tmrwweather", helper.Translation.Get("console-text.desc_tmrweather"), ConsoleCommands.TomorrowWeatherChangeFromConsole) .Add("world_setweather", helper.Translation.Get("console-text.desc_setweather"), ConsoleCommands.WeatherChangeFromConsole) .Add("debug_clearspecial", "debug command to clear special weathers", ConsoleCommands.ClearSpecial) .Add("debug_weatherstatus", "!", ConsoleCommands.OutputWeather) .Add("debug_sswa", "Show Special Weather", ConsoleCommands.ShowSpecialWeather) .Add("debug_vrainc", "Set Rain Amt.", ConsoleCommands.SetRainAmt) .Add("debug_raintotal", "Get Rain Total", ConsoleCommands.DisplayRainTotal) .Add("debug_printClimate", "Print Climate Tracker Data", ConsoleCommands.DisplayClimateTrackerData); }
public Theater(TileSet tileset, Action <uint, string> onMissingImage = null) { this.tileset = tileset; var allocated = false; Func <Sheet> allocate = () => { if (allocated) { throw new SheetOverflowException("Terrain sheet overflow. Try increasing the tileset SheetSize parameter."); } allocated = true; return(new Sheet(SheetType.Indexed, new Size(tileset.SheetSize, tileset.SheetSize))); }; random = new MersenneTwister(); var frameCache = new FrameCache(Game.ModData.DefaultFileSystem, Game.ModData.SpriteLoaders); foreach (var t in tileset.Templates) { var variants = new List <Sprite[]>(); foreach (var i in t.Value.Images) { ISpriteFrame[] allFrames; if (onMissingImage != null) { try { allFrames = frameCache[i]; } catch (FileNotFoundException) { onMissingImage(t.Key, i); continue; } } else { allFrames = frameCache[i]; } var frameCount = tileset.EnableDepth ? allFrames.Length / 2 : allFrames.Length; var indices = t.Value.Frames != null ? t.Value.Frames : Exts.MakeArray(t.Value.TilesCount, j => j); var start = indices.Min(); var end = indices.Max(); if (start < 0 || end >= frameCount) { throw new YamlException("Template `{0}` uses frames [{1}..{2}] of {3}, but only [0..{4}] actually exist" .F(t.Key, start, end, i, frameCount - 1)); } variants.Add(indices.Select(j => { var f = allFrames[j]; var tile = t.Value.Contains(j) ? t.Value[j] : null; // The internal z axis is inverted from expectation (negative is closer) var zOffset = tile != null ? -tile.ZOffset : 0; var zRamp = tile != null ? tile.ZRamp : 1f; var offset = new float3(f.Offset, zOffset); var type = SheetBuilder.FrameTypeToSheetType(f.Type); // Defer SheetBuilder creation until we know what type of frames we are loading! // TODO: Support mixed indexed and BGRA frames if (sheetBuilder == null) { sheetBuilder = new SheetBuilder(SheetBuilder.FrameTypeToSheetType(f.Type), allocate); } else if (type != sheetBuilder.Type) { throw new YamlException("Sprite type mismatch. Terrain sprites must all be either Indexed or RGBA."); } var s = sheetBuilder.Allocate(f.Size, zRamp, offset); Util.FastCopyIntoChannel(s, f.Data); if (tileset.EnableDepth) { var ss = sheetBuilder.Allocate(f.Size, zRamp, offset); Util.FastCopyIntoChannel(ss, allFrames[j + frameCount].Data); // s and ss are guaranteed to use the same sheet // because of the custom terrain sheet allocation s = new SpriteWithSecondaryData(s, s.Sheet, ss.Bounds, ss.Channel); } return(s); }).ToArray()); } var allSprites = variants.SelectMany(s => s); // Ignore the offsets baked into R8 sprites if (tileset.IgnoreTileSpriteOffsets) { allSprites = allSprites.Select(s => new Sprite(s.Sheet, s.Bounds, s.ZRamp, new float3(float2.Zero, s.Offset.Z), s.Channel, s.BlendMode)); } if (onMissingImage != null && !variants.Any()) { continue; } templates.Add(t.Value.Id, new TheaterTemplate(allSprites.ToArray(), variants.First().Count(), t.Value.Images.Length)); } // 1x1px transparent tile missingTile = sheetBuilder.Add(new byte[sheetBuilder.Type == SheetType.BGRA ? 4 : 1], new Size(1, 1)); Sheet.ReleaseBuffer(); }
void ICreatePlayersInfo.CreateServerPlayers(MapPreview map, Session lobbyInfo, List <GameInformation.Player> players, MersenneTwister playerRandom) { throw new NotImplementedException("EditorActorLayer must not be defined on the world actor"); }
public static T Random <T>(this IEnumerable <T> ts, MersenneTwister r) { var xs = ts.ToArray(); return(xs[r.Next(xs.Length)]); }
private static void GenerateJD_PriceMatrixValues(double volatility, double riskFreeOptionPrice, MersenneTwister random, double dT, List <Tuple <double, double[]> > jdPriceMatrix, double jumpDrift, int simulations) { for (var i = 1; i < EnvironmentSettings.Instance.TimeIntervals + 1; i++) { var gaussPrice = Normal.WithMeanStdDev(0.0, 1.0, random).Samples().Take(simulations).ToArray(); var gaussJump = Normal.WithMeanStdDev(0.0, 1.0, random).Samples().Take(simulations).ToArray(); var poissonJump = Poisson.Samples(EnvironmentSettings.Instance.JumpLambda * dT).Take(simulations).ToArray(); var S = Simulation_JD(riskFreeOptionPrice, dT, volatility, gaussPrice, gaussJump, poissonJump, jdPriceMatrix[i - 1], jumpDrift, simulations); jdPriceMatrix.Add(new Tuple <double, double[]>(i * dT, S)); } }
public static T Random <T>(this IEnumerable <T> ts, MersenneTwister r) { return(Random(ts, r, true)); }
public double GetStormOdds(SDate Target, MersenneTwister dice, StringBuilder Debug) { return(this.GetClimateForDate(Target).RetrieveOdds(dice, "storm", Target.Day, Debug)); }
// Sampled a N-sample probability density function in the range [-1024..1024] // 1 sample produces a rectangular probability // 2 samples produces a triangular probability // ... // N samples approximates a true gaussian public static WDist FromPDF(MersenneTwister r, int samples) { return(new WDist(Exts.MakeArray(samples, _ => r.Next(-1024, 1024)) .Sum() / samples)); }
public Theater(TileSet tileset) { this.tileset = tileset; var allocated = false; Func <Sheet> allocate = () => { if (allocated) { throw new SheetOverflowException("Terrain sheet overflow.Try increasing the tileset SheetSize parameter."); } allocated = true; return(new Sheet(SheetT.Indexed, new Size(tileset.SheetSize, tileset.SheetSize))); }; sheetBuilder = new SheetBuilder(SheetT.Indexed, allocate); random = new MersenneTwister(); var frameCache = new FrameCache(WarGame.ModData.DefaultFileSystem, WarGame.ModData.SpriteLoaders); foreach (var t in tileset.Templates) { var variants = new List <Sprite[]>(); foreach (var i in t.Value.Images) { var allFrames = frameCache[i]; var frameCount = tileset.EnableDepth ? allFrames.Length / 2 : allFrames.Length; var indices = t.Value.Frames != null ? t.Value.Frames : Enumerable.Range(0, frameCount); variants.Add(indices.Select(j => { var f = allFrames[j]; var tile = t.Value.Contains(j)?t.Value[j]:null; //The internal z axis is inverted from expectation (negative is closer) var zOffset = tile != null ? -tile.ZOffset : 0; var zRamp = tile != null ? tile.ZRamp : 1f; var offset = new Vector3(f.Offset, zOffset); var s = sheetBuilder.Allocate(f.Size, zRamp, offset); Util.FastCopyIntoChannel(s, f.Data); if (tileset.EnableDepth) { var ss = sheetBuilder.Allocate(f.Size, zRamp, offset); Util.FastCopyIntoChannel(ss, allFrames[j + frameCount].Data); //s and ss are guaranteed to use the same sheet because of the custom terrain sheet allocation. s = new SpriteWithSecondaryData(s, ss.Bounds, ss.Channel); } return(s); }).ToArray()); } var allSprites = variants.SelectMany(s => s); if (tileset.IgnoreTileSpriteOffsets) { allSprites = allSprites.Select(s => new Sprite(s.Sheet, s.Bounds, s.ZRamp, new Vector3(Vector2.Zero, s.Offset.Z), s.Channel, s.BlendMode)); } templates.Add(t.Value.Id, new TheaterTemplate(allSprites.ToArray(), variants.First().Count(), t.Value.Images.Length)); } missingTile = sheetBuilder.Add(new byte[1], new Size(1, 1)); Sheet.ReleaseBuffer(); }
/// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { RWeatherIcon = new Rectangle(); WeatherOpt = helper.ReadConfig <WeatherConfig>(); Logger = Monitor; Translator = Helper.Translation; Reflection = Helper.Reflection; MPHandler = Helper.Multiplayer; Dice = new MersenneTwister(); OurIcons = new Sprites.Icons(Helper.Content); WeatherProcessing.Init(); Conditions = new WeatherConditions(); DescriptionEngine = new Descriptions(WeatherOpt, Helper.Translation); queuedMsg = null; SummitRebornLoaded = false; if (WeatherOpt.Verbose) { Monitor.Log($"Loading climate type: {WeatherOpt.ClimateType} from file", LogLevel.Trace); } var path = Path.Combine("assets", "climates", WeatherOpt.ClimateType + ".json"); GameClimate = helper.Data.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) { return; } var harmony = HarmonyInstance.Create("koihimenakamura.climatesofferngill"); harmony.Patch( original: AccessTools.Method(typeof(GameLocation), "drawAboveAlwaysFrontLayer"), transpiler: new HarmonyMethod(AccessTools.Method(typeof(GameLocationPatches), "DAAFLTranspiler"))); Monitor.Log("Patching GameLocation::drawAboveAlwaysFrontLayer with a Transpiler.", LogLevel.Trace); harmony.Patch( original: AccessTools.Method(typeof(Game1), "drawWeather"), prefix: new HarmonyMethod(AccessTools.Method(typeof(Game1Patches), "DrawWeatherPrefix"))); Monitor.Log("Patching Game1::drawWeather with a prefix method.", LogLevel.Trace); harmony.Patch( original: AccessTools.Method(typeof(Game1), "updateWeather"), prefix: new HarmonyMethod(AccessTools.Method(typeof(Game1Patches), "UpdateWeatherPrefix"))); Monitor.Log("Patching Game1::updateWeather with a prefix method.", LogLevel.Trace); harmony.Patch( original: AccessTools.Method(AccessTools.TypeByName("StardewModdingAPI.Framework.SGame"), "DrawImpl"), transpiler: new HarmonyMethod(AccessTools.Method(typeof(SGamePatches), "DrawImplTranspiler"))); Monitor.Log("Patching SMAPI (SGame::DrawImpl) with a transpiler.", LogLevel.Trace); harmony.Patch( original: AccessTools.Constructor(AccessTools.TypeByName("StardewValley.WeatherDebris"), new[] { typeof(Vector2), typeof(int), typeof(float), typeof(float), typeof(float) }), postfix: new HarmonyMethod(AccessTools.Method(typeof(WeatherDebrisPatches), "CtorPostfix"))); Monitor.Log("Patching WeatherDebris's constructor method with a postfix method.", LogLevel.Trace); harmony.Patch( original: AccessTools.Method(typeof(WeatherDebris), "draw"), prefix: new HarmonyMethod(AccessTools.Method(typeof(WeatherDebrisPatches), "DrawPrefix"))); Monitor.Log("Patching WeatherDebris::draw with a prefix method.", LogLevel.Trace); harmony.Patch( original: AccessTools.Method(typeof(WeatherDebris), "update", new[] { typeof(bool) }), prefix: new HarmonyMethod(AccessTools.Method(typeof(WeatherDebrisPatches), "UpdatePrefix"))); Monitor.Log("Patching WeatherDebris::draw with a prefix method.", LogLevel.Trace); //INSERT DNT CHECKS HERE var modManifest = Helper.ModRegistry.Get("knakamura.dynamicnighttime"); if (modManifest != null) { if (modManifest.Manifest.Version.IsOlderThan("1.2.11")) { Monitor.Log("WARNING: Overcast weather may not work correctly unless you are running Dynamic Night Time 1.2.11 or later", LogLevel.Alert); } } else { harmony.Patch( original: AccessTools.Method(typeof(Game1), "UpdateGameClock"), postfix: new HarmonyMethod(AccessTools.Method(typeof(GameClockPatch), "Postfix"))); Monitor.Log("Patching Game1::UpdateGameClock with a Postfix method. (Used only when Climates is installed and DNT is not.)", LogLevel.Trace); } ConsoleCommands.Init(); SanityCheckConfigOptions(); //subscribe to events var events = helper.Events; events.GameLoop.DayStarted += OnDayStarted; events.GameLoop.Saving += OnSaving; events.GameLoop.TimeChanged += OnTimeChanged; events.Display.MenuChanged += OnMenuChanged; events.GameLoop.UpdateTicked += OnUpdateTicked; events.GameLoop.GameLaunched += OnGameLaunched; events.GameLoop.OneSecondUpdateTicked += OnOneSecondUpdateTicked; events.GameLoop.ReturnedToTitle += OnReturnedToTitle; events.GameLoop.SaveLoaded += OnSaveLoaded; events.Display.RenderingHud += OnRenderingHud; events.Display.RenderedHud += OnRenderedHud; events.Input.ButtonPressed += OnButtonPressed; events.Multiplayer.ModMessageReceived += OnModMessageRecieved; //console commands helper.ConsoleCommands .Add("world_tmrwweather", helper.Translation.Get("console-text.desc_tmrweather"), ConsoleCommands.TomorrowWeatherChangeFromConsole) .Add("world_setweather", helper.Translation.Get("console-text.desc_setweather"), ConsoleCommands.WeatherChangeFromConsole) .Add("debug_clearspecial", "debug command to clear special weathers", ConsoleCommands.ClearSpecial) .Add("debug_weatherstatus", "!", ConsoleCommands.OutputWeather) .Add("debug_sswa", "Show Special Weather", ConsoleCommands.ShowSpecialWeather) .Add("debug_vrainc", "Set Rain Amt.", ConsoleCommands.SetRainAmt) .Add("debug_raindef", "Set Rain Deflection.", ConsoleCommands.SetRainDef) /* * .Add("debug_setwindchance", "Set Wind Chance", ConsoleCommands.SetWindChance) * .Add("debug_setwindtresh", "Set Wind Threshold", ConsoleCommands.SetWindThreshold) * .Add("debug_setwindrange", "Set Wind Range", ConsoleCommands.SetWindRange) * .Add("debug_raintotal", "Get Rain Total", ConsoleCommands.DisplayRainTotal) * .Add("debug_getcurrentwind", "Show wind values", ConsoleCommands.ShowWind) * .Add("debug_resetwind", "Reset Global Wind", ConsoleCommands.ResetGlobalWind) */ .Add("debug_printClimate", "Print Climate Tracker Data", ConsoleCommands.DisplayClimateTrackerData); }
internal static void DynamicRainOnNewDay(WeatherConditions curr, MersenneTwister Dice) { if (!curr.HasWeather(CurrentWeather.Rain)) { return; } curr.SetRainAmt(70); //Rain chances. This will also affect storms (in that storms still can have variable rain) . //only roll this if it's actually raining. :| double roll = Dice.NextDouble(); if (roll <= ClimatesOfFerngill.WeatherOpt.VariableRainChance && Game1.isRaining) { ClimatesOfFerngill.Logger.Log($"With {roll}, we are setting for variable rain against {ClimatesOfFerngill.WeatherOpt.VariableRainChance}"); curr.SetVariableRain(true); //check for overcast chance first. if (Dice.NextDouble() < ClimatesOfFerngill.WeatherOpt.OvercastChance && !Game1.isLightning) { WeatherUtilities.SetWeatherOvercast(true); SDVUtilities.AlterWaterStatusOfCrops(water: false); SDVUtilities.ShowMessage(ClimatesOfFerngill.Translator.Get("hud-text.desc_overcast"), 0); } //now that we've done that base check, we need to change the rainfall... //... after we calc rainfall to see if it's watered. Essentially, every time this is called, //... it'll check to see if it should flip the tiles. //Variable Rain may set the starting rain at 0300 to be something else than normal, and as such, StartingRain should // only be checked if IsVariableRain is true. // Odds are fixed: Normal (default) is 72%, Light is 16%, Heavy is 6%, Sunshower is 5%, Severe is 1% double startingRainRoll = Dice.NextDouble(); if (startingRainRoll <= .72) { curr.StartingRain = RainLevels.Normal; } else if (startingRainRoll > .72 && startingRainRoll <= .88) { curr.StartingRain = RainLevels.Light; } else if (startingRainRoll > .88 && startingRainRoll <= .94) { curr.StartingRain = RainLevels.Heavy; } else if (startingRainRoll > .94 && startingRainRoll <= .99) { curr.StartingRain = RainLevels.Sunshower; } else if (startingRainRoll > .99) { curr.StartingRain = RainLevels.Severe; } if (Game1.isLightning && !(curr.StartingRain == RainLevels.Light || curr.StartingRain == RainLevels.Sunshower || curr.StartingRain == RainLevels.Normal)) { curr.StartingRain = RainLevels.Heavy; } curr.SetRainAmt(WeatherUtilities.GetRainCategoryMidPoint(curr.StartingRain)); curr.TodayRain = curr.AmtOfRainDrops; //now run this for 0300 to 0600. for (int i = 0; i < 17; i++) { curr.SetRainAmt(GetNewRainAmount(curr.AmtOfRainDrops, ClimatesOfFerngill.Translator)); curr.TodayRain += curr.AmtOfRainDrops; } //set starting amount at 6am curr.RefreshRainAmt(); } }
/// <summary> /// Run example /// </summary> /// <seealso cref="http://en.wikipedia.org/wiki/Random_number_generation">Random number generation</seealso> /// <seealso cref="http://en.wikipedia.org/wiki/Linear_congruential_generator">Linear congruential generator</seealso> /// <seealso cref="http://en.wikipedia.org/wiki/Mersenne_twister">Mersenne twister</seealso> /// <seealso cref="http://en.wikipedia.org/wiki/Lagged_Fibonacci_generator">Lagged Fibonacci generator</seealso> /// <seealso cref="http://en.wikipedia.org/wiki/Xorshift">Xorshift</seealso> public void Run() { // All RNG classes in MathNet have next counstructors: // - RNG(int seed, bool threadSafe): initializes a new instance with specific seed value and thread safe property // - RNG(int seed): iуууnitializes a new instance with specific seed value. Thread safe property is set to Control.ThreadSafeRandomNumberGenerators // - RNG(bool threadSafe) : initializes a new instance with the seed value set to DateTime.Now.Ticks and specific thread safe property // - RNG(bool threadSafe) : initializes a new instance with the seed value set to DateTime.Now.Ticks and thread safe property set to Control.ThreadSafeRandomNumberGenerators // All RNG classes in MathNet have next methods to produce random values: // - double[] NextDouble(int n): returns an "n"-size array of uniformly distributed random doubles in the interval [0.0,1.0]; // - int Next(): returns a nonnegative random number; // - int Next(int maxValue): returns a random number less then a specified maximum; // - int Next(int minValue, int maxValue): returns a random number within a specified range; // - void NextBytes(byte[] buffer): fills the elements of a specified array of bytes with random numbers; // All RNG classes in MathNet have next extension methods to produce random values: // - long NextInt64(): returns a nonnegative random number less than "Int64.MaxValue"; // - int NextFullRangeInt32(): returns a random number of the full Int32 range; // - long NextFullRangeInt64(): returns a random number of the full Int64 range; // - decimal NextDecimal(): returns a nonnegative decimal floating point random number less than 1.0; // 1. Multiplicative congruential generator using a modulus of 2^31-1 and a multiplier of 1132489760 var mcg31M1 = new Mcg31m1(1); Console.WriteLine(@"1. Generate 10 random double values using Multiplicative congruential generator with a modulus of 2^31-1 and a multiplier of 1132489760"); var randomValues = mcg31M1.NextDouble(10); for (var i = 0; i < randomValues.Length; i++) { Console.Write(randomValues[i].ToString("N") + @" "); } Console.WriteLine(); Console.WriteLine(); // 2. Multiplicative congruential generator using a modulus of 2^59 and a multiplier of 13^13 var mcg59 = new Mcg59(1); Console.WriteLine(@"2. Generate 10 random integer values using Multiplicative congruential generator with a modulus of 2^59 and a multiplier of 13^13"); for (var i = 0; i < 10; i++) { Console.Write(mcg59.Next() + @" "); } Console.WriteLine(); Console.WriteLine(); // 3. Random number generator using Mersenne Twister 19937 algorithm var mersenneTwister = new MersenneTwister(1); Console.WriteLine(@"3. Generate 10 random integer values less then 100 using Mersenne Twister 19937 algorithm"); for (var i = 0; i < 10; i++) { Console.Write(mersenneTwister.Next(100) + @" "); } Console.WriteLine(); Console.WriteLine(); // 4. Multiple recursive generator with 2 components of order 3 var mrg32K3A = new Mrg32k3a(1); Console.WriteLine(@"4. Generate 10 random integer values in range [50;100] using multiple recursive generator with 2 components of order 3"); for (var i = 0; i < 10; i++) { Console.Write(mrg32K3A.Next(50, 100) + @" "); } Console.WriteLine(); Console.WriteLine(); // 5. Parallel Additive Lagged Fibonacci pseudo-random number generator var palf = new Palf(1); Console.WriteLine(@"5. Generate 10 random bytes using Parallel Additive Lagged Fibonacci pseudo-random number generator"); var bytes = new byte[10]; palf.NextBytes(bytes); for (var i = 0; i < bytes.Length; i++) { Console.Write(bytes[i] + @" "); } Console.WriteLine(); Console.WriteLine(); // 6. A random number generator based on the "System.Security.Cryptography.RandomNumberGenerator" class in the .NET library var systemCryptoRandomNumberGenerator = new SystemCryptoRandomNumberGenerator(); Console.WriteLine(@"6. Generate 10 random decimal values using RNG based on the 'System.Security.Cryptography.RandomNumberGenerator'"); for (var i = 0; i < 10; i++) { Console.Write(systemCryptoRandomNumberGenerator.NextDecimal().ToString("N") + @" "); } Console.WriteLine(); Console.WriteLine(); // 7. Wichmann-Hill’s 1982 combined multiplicative congruential generator var rngWh1982 = new WH1982(); Console.WriteLine(@"7. Generate 10 random full Int32 range values using Wichmann-Hill’s 1982 combined multiplicative congruential generator"); for (var i = 0; i < 10; i++) { Console.Write(rngWh1982.NextFullRangeInt32() + @" "); } Console.WriteLine(); Console.WriteLine(); // 8. Wichmann-Hill’s 2006 combined multiplicative congruential generator. var rngWh2006 = new WH2006(); Console.WriteLine(@"8. Generate 10 random full Int64 range values using Wichmann-Hill’s 2006 combined multiplicative congruential generator"); for (var i = 0; i < 10; i++) { Console.Write(rngWh2006.NextFullRangeInt32() + @" "); } Console.WriteLine(); Console.WriteLine(); // 9. Multiply-with-carry Xorshift pseudo random number generator var xorshift = new Xorshift(); Console.WriteLine(@"9. Generate 10 random nonnegative values less than Int64.MaxValue using Multiply-with-carry Xorshift pseudo random number generator"); for (var i = 0; i < 10; i++) { Console.Write(xorshift.NextInt64() + @" "); } Console.WriteLine(); }
/// <summary> /// Construct /// </summary> public RandomGenerator() { _rGen = new MersenneTwister(); }
public RandomAdaptor(MersenneTwister mersenneTwister) { this.mersenneTwister = mersenneTwister; }
static void Main(string[] args) { Console.WriteLine("Random Algorithm Timing"); Console.WriteLine("======================="); Console.Write("Calculating pre-instantiated times..."); var preinstantiatedResults = new List <TimingResult>(); var systemRandom = new System.Random(); preinstantiatedResults.Add(RunTest("System.Random", () => systemRandom.Next())); var systemRandomWrapper = new SystemRandomWrapper(); preinstantiatedResults.Add(RunTest("SystemRandomWrapper", () => systemRandomWrapper.Next())); var xorShift = new XorShift(); preinstantiatedResults.Add(RunTest("XorShift", () => xorShift.Next())); var linearCongruential = new LinearCongruential(); preinstantiatedResults.Add(RunTest("LinearCongruential", () => linearCongruential.Next())); var mersenneTwister = new MersenneTwister(); preinstantiatedResults.Add(RunTest("MersenneTwister", () => mersenneTwister.Next())); var motherOfAll = new MotherOfAll(); preinstantiatedResults.Add(RunTest("MotherOfAll", () => motherOfAll.Next())); var ranrotB = new RanrotB(); preinstantiatedResults.Add(RunTest("RanrotB", () => ranrotB.Next())); var wellEquidistributedLongPeriodLinear = new WellEquidistributedLongPeriodLinear(); preinstantiatedResults.Add(RunTest("W.E.L.L.", () => wellEquidistributedLongPeriodLinear.Next())); Console.SetCursorPosition(0, Console.CursorTop); DisplayResults("Results of pre-instantiated random objects:", preinstantiatedResults); Console.Write("Calculating non-instantiated times..."); var noninstantiatedResults = new List <TimingResult>(); noninstantiatedResults.Add(RunTest("System.Random", () => { var random = new System.Random(); random.Next(); })); noninstantiatedResults.Add(RunTest("SystemRandomWrapper", () => { var random = new SystemRandomWrapper(); random.Next(); })); noninstantiatedResults.Add(RunTest("XorShift", () => { var random = new XorShift(); random.Next(); })); noninstantiatedResults.Add(RunTest("LinearCongruential", () => { var random = new LinearCongruential(); random.Next(); })); noninstantiatedResults.Add(RunTest("MersenneTwister", () => { var random = new MersenneTwister(); random.Next(); })); noninstantiatedResults.Add(RunTest("MotherOfAll", () => { var random = new MotherOfAll(); random.Next(); })); noninstantiatedResults.Add(RunTest("RanrotB", () => { var random = new RanrotB(); random.Next(); })); noninstantiatedResults.Add(RunTest("W.E.L.L.", () => { var random = new WellEquidistributedLongPeriodLinear(); random.Next(); })); Console.SetCursorPosition(0, Console.CursorTop); DisplayResults("Results of non-instantiated random objects:", noninstantiatedResults); }
public string GetRandomExistingSequence(string[] sequences, MersenneTwister random) { return(sequences.Where(s => HasSequence(s)).RandomOrDefault(random)); }
public void SampleKnownIntegerValuesSeed42() { var mt = new MersenneTwister(42); Assert.AreEqual(mt.Next(), 804318771); }
public Laser(ProjectileArgs args, LaserInfo info) { this.info = info; colors = new Color[info.Radius]; for (var i = 0; i < info.Radius; i++) { var color = info.Color == Color.Transparent ? args.SourceActor.Owner.Color.RGB : info.Color; var bw = (float)((info.InnerLightness - info.OuterLightness) * i / (info.Radius - 1) + info.OuterLightness) / 0xff; var dstR = bw > .5 ? 1 - (1 - 2 * (bw - .5)) * (1 - (float)color.R / 0xff) : 2 * bw * ((float)color.R / 0xff); var dstG = bw > .5 ? 1 - (1 - 2 * (bw - .5)) * (1 - (float)color.G / 0xff) : 2 * bw * ((float)color.G / 0xff); var dstB = bw > .5 ? 1 - (1 - 2 * (bw - .5)) * (1 - (float)color.B / 0xff) : 2 * bw * ((float)color.B / 0xff); colors[i] = Color.FromArgb((int)(dstR * 0xff), (int)(dstG * 0xff), (int)(dstB * 0xff)); } var direction = args.PassiveTarget - args.Source; if (info.Distortion != 0 || info.DistortionAnimation != 0) { leftVector = new WVec(direction.Y, -direction.X, 0); if (leftVector.Length != 0) { leftVector = 1024 * leftVector / leftVector.Length; } upVector = new WVec( -direction.X * direction.Z, -direction.Z * direction.Y, direction.X * direction.X + direction.Y * direction.Y); if (upVector.Length != 0) { upVector = 1024 * upVector / upVector.Length; } random = args.SourceActor.World.SharedRandom; } if (this.info.SegmentLength == WDist.Zero) { offsets = new[] { args.Source, args.PassiveTarget }; } else { var numSegments = (direction.Length - 1) / info.SegmentLength.Length + 1; offsets = new WPos[numSegments + 1]; offsets[0] = args.Source; offsets[offsets.Length - 1] = args.PassiveTarget; for (var i = 1; i < numSegments; i++) { var segmentStart = direction / numSegments * i; offsets[i] = args.Source + segmentStart; if (info.Distortion != 0) { 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; } } } args.Weapon.Impact(Target.FromPos(args.PassiveTarget), args.SourceActor, args.DamageModifiers); }