Exemple #1
0
        /// <summary>Accepts an event attendee with specified properties.</summary>
        /// <param name="age">The attendee age.</param>
        /// <param name="gender">The attendee gender.</param>
        /// <param name="education">The attendee education.</param>
        /// <param name="wealth">The attendee wealth.</param>
        /// <param name="wellbeing">The attendee wellbeing.</param>
        /// <param name="happiness">The attendee happiness.</param>
        /// <param name="randomizer">A reference to the game's randomizer.</param>
        /// <returns>
        /// <c>true</c> if the event attendee with specified properties is accepted and can attend this city event;
        /// otherwise, <c>false</c>.
        /// </returns>
        public override bool TryAcceptAttendee(
            Citizen.AgeGroup age,
            Citizen.Gender gender,
            Citizen.Education education,
            Citizen.Wealth wealth,
            Citizen.Wellbeing wellbeing,
            Citizen.Happiness happiness,
            IRandomizer randomizer)
        {
            if (attendeesCount > eventTemplate.Capacity)
            {
                return(false);
            }

            if (eventTemplate.Costs != null && eventTemplate.Costs.Entry > GetCitizenBudgetForEvent(wealth, randomizer))
            {
                return(false);
            }

            CityEventAttendees attendees = eventTemplate.Attendees;
            float randomPercentage       = randomizer.GetRandomValue(100u);

            if (!CheckAge(age, attendees, randomPercentage))
            {
                return(false);
            }

            randomPercentage = randomizer.GetRandomValue(100u);
            if (!CheckGender(gender, attendees, randomPercentage))
            {
                return(false);
            }

            randomPercentage = randomizer.GetRandomValue(100u);
            if (!CheckEducation(education, attendees, randomPercentage))
            {
                return(false);
            }

            randomPercentage = randomizer.GetRandomValue(100u);
            if (!CheckWealth(wealth, attendees, randomPercentage))
            {
                return(false);
            }

            randomPercentage = randomizer.GetRandomValue(100u);
            if (!CheckWellbeing(wellbeing, attendees, randomPercentage))
            {
                return(false);
            }

            randomPercentage = randomizer.GetRandomValue(100u);
            if (!CheckHappiness(happiness, attendees, randomPercentage))
            {
                return(false);
            }

            attendeesCount++;
            return(true);
        }
        /// <summary>
        /// Construct a neural genetic algorithm.
        /// </summary>
        ///
        /// <param name="network">The network to base this on.</param>
        /// <param name="randomizer">The randomizer used to create this initial population.</param>
        /// <param name="calculateScore">The score calculation object.</param>
        /// <param name="populationSize">The population size.</param>
        /// <param name="mutationPercent">The percent of offspring to mutate.</param>
        /// <param name="percentToMate">The percent of the population allowed to mate.</param>
        public NeuralGeneticAlgorithm(BasicNetwork network,
            IRandomizer randomizer, ICalculateScore calculateScore,
            int populationSize, double mutationPercent,
            double percentToMate)
            : base(TrainingImplementationType.Iterative)
        {
            Genetic = new NeuralGeneticAlgorithmHelper
                           {
                               CalculateScore = new GeneticScoreAdapter(calculateScore)
                           };
            IPopulation population = new BasicPopulation(populationSize);
            Genetic.MutationPercent = mutationPercent;
            Genetic.MatingPopulation = percentToMate*2;
            Genetic.PercentToMate = percentToMate;
            Genetic.Crossover = new Splice(network.Structure.CalculateSize()/3);
            Genetic.Mutate = new MutatePerturb(4.0d);
            Genetic.Population = population;
            for (int i = 0; i < population.PopulationSize; i++)
            {
                var chromosomeNetwork = (BasicNetwork) (network
                                                           .Clone());
                randomizer.Randomize(chromosomeNetwork);

                var genome = new NeuralGenome(chromosomeNetwork) {GA = Genetic};
                Genetic.PerformCalculateScore(genome);
                Genetic.Population.Add(genome);
            }
            population.Sort();
        }
Exemple #3
0
        public double[] LikelihoodWeighting(string X,
                                            Dictionary <string, bool?> evidence, int numberOfSamples,
                                            IRandomizer r)
        {
            var retval = new double[2];

            for (int i = 0; i < numberOfSamples; i++)
            {
                var x             = new Dictionary <string, bool?>();
                var w             = 1.0;
                var bayesNetNodes = this.GetVariableNodes();
                foreach (BayesNetNode node in bayesNetNodes)
                {
                    if (evidence[node.Variable] != null)
                    {
                        w *= node.ProbabilityOf(x);
                        x[node.Variable] = evidence[node.Variable];
                    }
                    else
                    {
                        x[node.Variable] = node.IsTrueFor(r.NextDouble(), x);
                    }
                }
                bool?queryValue = (x[X]);
                if (queryValue == true)
                {
                    retval[0] += w;
                }
                else
                {
                    retval[1] += w;
                }
            }
            return(Util.Util.Normalize(retval));
        }
Exemple #4
0
        /// <summary>
        /// Shuffle the input string using the given type
        /// </summary>
        /// <param name="input"> Input string</param>
        /// <param name="randomizer"> Randomizer to use </param>
        /// <returns>Shuffled string</returns>
        private string Shuffle(string input, IRandomizer randomizer)
        {
            // If the input is empty or of length 1 then just return the input string
            if (string.IsNullOrEmpty(input) || input.Length < 2)
            {
                return(input);
            }

            // We will just randomize string characters based on the input string's length
            // We could have chosen a random number but input length will add some more randomness
            int length = input.Length - 1;

            // Since strings are immutables, we will convert the input string to char array for easy swapping
            char[] charArray = input.ToArray <char>();

            // Just loop the length of the string and swap random characters
            for (int index = 0; index < length; index++)
            {
                int  rngIdx = randomizer.GetRandomInt(0, length); // Get a random index from the range
                char temp   = charArray[index];
                charArray[index]  = charArray[rngIdx];
                charArray[rngIdx] = temp;
            }

            return(new string(charArray));
        }
Exemple #5
0
        public LayoutGenerator(
            LayoutConfiguration layoutConfiguration,
            IRandomizer rand,
            SettingConfiguration baseConfiguration,
            ControlConfiguration controlConfiguration,
            Action <string> logAction = null)
        {
            _logAction = logAction;
            String errorMessage = "";

            if (!layoutConfiguration.isValid(out errorMessage))
            {
                throw new ArgumentException("LayoutConfiguration is not valid. " + errorMessage);
            }

            baseConfiguration.InventoryConfiguration.autogenerate();
            if (!baseConfiguration.InventoryConfiguration.isValid(layoutConfiguration.PodCapacity, out errorMessage))
            {
                throw new ArgumentException("InventoryConfiguration is not valid. " + errorMessage);
            }

            if (!controlConfiguration.IsValid(out errorMessage))
            {
                throw new ArgumentException("ControlConfiguration is not valid. " + errorMessage);
            }

            this.rand = rand;
            this.baseConfiguration = baseConfiguration;
            elevatorPositions      = new Dictionary <Tuple <double, double>, Elevator>();
            elevatorWaypoints      = new Dictionary <Elevator, List <Waypoint> >();
            elevatorSemaphores     = new Dictionary <Waypoint, QueueSemaphore>();
            instance      = Instance.CreateInstance(this.baseConfiguration, controlConfiguration);
            instance.Name = layoutConfiguration.NameLayout;
            this.lc       = layoutConfiguration;
        }
Exemple #6
0
 public ParticleManager(IEventAggregator eventAggregator, IDrawer drawer, IRandomizer randomizer)
 {
     _eventAggregator = eventAggregator;
     _drawer          = drawer;
     _randomizer      = randomizer;
     _particles       = new List <Particle>();
 }
 public CharacterBuilder(RaceRepository raceRepository, ClassRepository classRepository, IStatsComputer statsComputer, IRandomizer randomizer)
 {
     RaceRepository  = raceRepository;
     ClassRepository = classRepository;
     StatsComputer   = statsComputer;
     Randomizer      = randomizer;
 }
Exemple #8
0
    public StoryboardParserTests()
    {
        blockFactory = new FakeBlockFactory();
        dismissNodes = new();
        parsingContext = A.Fake<IParsingContext>(i => i.Strict());
        A.CallTo(() => parsingContext.RegisterDismissNode(A<INode>.Ignored))
            .Invokes(i => dismissNodes.Add(i.Arguments.Get<INode>(0)));
        A.CallTo(() => parsingContext.BlockFactory).Returns(blockFactory);

        rootBlockParser = A.Fake<IRootBlockParser>(i => i.Strict());
        sceneNavigator = A.Fake<ISceneNavigator>(i => i.Strict());
        eventManager = A.Fake<IEventManager>(i => i.Strict());
        randomizer = A.Fake<IRandomizer>(i => i.Strict());
        navigationState = A.Fake<INavigationState>(i => i.Strict());
        variableDictionary = A.Fake<IVariableDictionary>(i => i.Strict());
        blockState = A.Fake<IBlockState>(i => i.Strict());

        var serviceProvider = A.Fake<IServiceProvider>(i => i.Strict());
        A.CallTo(() => serviceProvider.GetService(typeof(IParsingContext))).Returns(parsingContext);
        A.CallTo(() => serviceProvider.GetService(typeof(IRootBlockParser))).Returns(rootBlockParser);
        A.CallTo(() => serviceProvider.GetService(typeof(ISceneNavigator))).Returns(sceneNavigator);
        A.CallTo(() => serviceProvider.GetService(typeof(IEventManager))).Returns(eventManager);
        A.CallTo(() => serviceProvider.GetService(typeof(IRandomizer))).Returns(randomizer);
        A.CallTo(() => serviceProvider.GetService(typeof(INavigationState))).Returns(navigationState);
        A.CallTo(() => serviceProvider.GetService(typeof(IVariableDictionary))).Returns(variableDictionary);
        A.CallTo(() => serviceProvider.GetService(typeof(IBlockState))).Returns(blockState);
        sut = new StoryboardParser(serviceProvider);
    }
Exemple #9
0
 public void Setup()
 {
     _fieldFactory = new FakeFieldFactory();
     _randomizer   = Substitute.For <IRandomizer>();
     _randomizer.GetNext().Returns((uint)2);
     _uut = new Roulette(_fieldFactory, _randomizer);
 }
Exemple #10
0
 public EvaluationContext(
     string name,
     ISpiceNetlistCaseSensitivitySettings caseSettings,
     IRandomizer randomizer,
     IExpressionParserFactory expressionParserFactory,
     IExpressionFeaturesReader expressionFeaturesReader,
     IExpressionValueProvider expressionValueProvider,
     INameGenerator nameGenerator,
     IResultService resultService)
 {
     _caseSettings            = caseSettings;
     ExpressionParserFactory  = expressionParserFactory;
     ExpressionFeaturesReader = expressionFeaturesReader;
     ExpressionValueProvider  = expressionValueProvider;
     NameGenerator            = nameGenerator;
     ResultService            = resultService;
     Name               = name;
     Parameters         = new Dictionary <string, Expression>(StringComparerProvider.Get(caseSettings.IsParameterNameCaseSensitive));
     Arguments          = new Dictionary <string, Expression>(StringComparerProvider.Get(caseSettings.IsParameterNameCaseSensitive));
     Functions          = new Dictionary <string, List <IFunction> >(StringComparerProvider.Get(caseSettings.IsFunctionNameCaseSensitive));
     Children           = new List <EvaluationContext>();
     ExpressionRegistry = new ExpressionRegistry(caseSettings.IsParameterNameCaseSensitive, caseSettings.IsExpressionNameCaseSensitive);
     FunctionsBody      = new Dictionary <string, string>();
     FunctionArguments  = new Dictionary <string, List <string> >();
     Randomizer         = randomizer;
 }
Exemple #11
0
 public Roulette(IFieldGenerator fieldGenerator, IRandomizer randomizer)
 {
     _fieldGenerator = fieldGenerator;
     _randomizer     = randomizer;
     _fields         = _fieldGenerator.CreateFields();
     _result         = _fields[0];
 }
Exemple #12
0
        public void ProcessMap(Map <T> map, DungeonConfiguration configuration, IRandomizer randomizer)
        {
            var deadends = map.AllCells.Where(cell => cell.Sides.Values.Count(type => type) == 1).ToList();

            foreach (var cell in deadends)
            {
                if (randomizer.GetRandomDouble() > configuration.ChanceToRemoveDeadends)
                {
                    continue;
                }

                var currentCell  = cell;
                var previousCell = map.GetAdjacentCell(cell, cell.Sides.First(pair => pair.Value).Key);
                var connected    = false;
                while (!connected)
                {
                    var direction = GetRandomValidDirection(map, currentCell, previousCell, randomizer);
                    if (!direction.HasValue)
                    {
                        break;
                    }

                    var adjacentCell = map.GetAdjacentCell(currentCell, direction.Value);
                    connected           = adjacentCell.IsOpen;
                    adjacentCell.IsOpen = true;
                    currentCell.Sides[direction.Value] = adjacentCell.Sides[direction.Value.Opposite()] = true;
                    previousCell = currentCell;
                    currentCell  = adjacentCell;
                }
            }
        }
Exemple #13
0
        public static IZooDatabase FromFile(IRandomizer randomizer, IAnimalNamesDatabase animalNamesDatabase, string filename, bool createIfNotExist = true)
        {
            var database = new ZooDatabase(randomizer, animalNamesDatabase, filename);

            if (createIfNotExist &&
                !File.Exists(filename))
            {
                database.Save(); // force generate an empty database file
                return(database);
            }

            var doc = new XmlDocument();

            doc.Load(filename);

            foreach (XmlNode node in doc.SelectNodes("Zoo/Animals/Animal"))
            {
                // attempt to find the animal type by full name
                var type = Assembly.GetExecutingAssembly().GetType(node.Attributes["Type"].InnerText);
                if (type != null)
                {
                    var id   = Guid.Parse(node.Attributes["Id"].InnerText);
                    var name = node.Attributes["Name"].InnerText;
                    var age  = new TimeSpan(long.Parse(node.Attributes["Age"].InnerText));

                    // construct an instance of the animal
                    var animal = ConstructAnimal(type, id, name, age);

                    // add animal to database (not saved yet)
                    database._animals.Add(animal.Id, animal);
                }
            }

            return(database);
        }
Exemple #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultDropGenerator" /> class.
 /// </summary>
 /// <param name="config">The configuration.</param>
 /// <param name="randomizer">The randomizer.</param>
 public DefaultDropGenerator(GameConfiguration config, IRandomizer randomizer)
 {
     this.baseGroups     = config.BaseDropItemGroups;
     this.randomizer     = randomizer;
     this.droppableItems = config.Items.Where(i => i.DropsFromMonsters).ToList();
     this.ancientItems   = this.droppableItems.Where(i => i.PossibleItemSetGroups.Any(o => o.Items.Any(n => n.BonusOption.OptionType == ItemOptionTypes.AncientBonus))).ToList();
 }
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var garcPath  = Path.Combine(this.gameDirectory, "RomFS", "a");
                var garcCount = Directory.GetFiles(garcPath, "*", SearchOption.AllDirectories).Length;
                this.game       = new GameConfig(garcCount);
                this.randomizer = Randomizer.GetRandomizer(this.game, this.config);

                await this.game.Initialize(this.gameDirectory, this.gameLanguage);

                this.mainPage = new RandomizerPage(this.randomizer);
                this.Content  = this.mainPage;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this,
                                $"An error occurred while loading the game:\n\n" +
                                $"{ex.Message}",
                                "Error Loading Game",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
                this.Close();
                Application.Current.MainWindow?.Show();
            }
        }
Exemple #16
0
        public static IEnumerable <T> TakeRandomFrom <T>(this IRandomizer randomizer, IEnumerable <T> source, int count)
        {
            var availableCount = source.Count();

            if (availableCount == 0)
            {
                throw new Exception("Unable to pick random number from empty list");
            }
            if (availableCount == count)
            {
                return(source);
            }

            var randomElements = new List <T>();

            for (var i = 0; i < count; i++)
            {
                var random        = randomizer.Random(0, availableCount - 1);
                var randomElement = source.Skip(random).First();
                if (randomElements.Contains(randomElement))
                {
                    i--;
                    continue;
                }
                randomElements.Add(randomElement);
            }
            return(randomElements);
        }
Exemple #17
0
        public MDPPerception <TState> Execute(TAction action, IRandomizer r)
        {
            MDPPerception <TState> perception = this.MDP.Execute(this.CurrentState, action, r);

            this.UpdateFromPerception(perception);
            return(perception);
        }
        public ParticleSet PerceptionUpdate(string perception, IRandomizer r)
        {
            // compute Particle Weight
            foreach (Particle p in particles)
            {
                double particleWeight = hmm.SensorModel.Get(p.State, perception);
                p.Weight = particleWeight;
            }

            // weighted sample to create new ParticleSet
            ParticleSet result = new ParticleSet(hmm);

            while (result.Count != Count)
            {
                foreach (Particle p in particles)
                {
                    double probability = r.NextDouble();
                    if (probability <= p.Weight)
                    {
                        if (result.Count < Count)
                        {
                            result.Add(new Particle(p.State, p.Weight));
                        }
                    }
                }
            }
            return(result);
        }
Exemple #19
0
        public void ProcessMap(Map <T> map, DungeonConfiguration configuration, IRandomizer randomizer)
        {
            var isolatedRooms = map.Rooms.Where(room => map.GetCellsAdjacentToRoom(room).All(cell => cell.Terrain == TerrainType.Rock)).ToList();

            foreach (var room in map.Rooms)
            {
                if (isolatedRooms.Contains(room))
                {
                    ConnectRoom(map, randomizer, room, isolatedRooms);
                }
                //place doors
                foreach (var cell in map.GetCellsAdjacentToRoom(room)
                         .Where(cell => cell.Terrain == TerrainType.Floor &&
                                map.GetAllAdjacentCells(cell).All(c => c.Terrain != TerrainType.Door)))
                {
                    //don't place a door if it leads to nowhere
                    if (map.GetAllAdjacentCells(cell).Count(c => c.Terrain == TerrainType.Floor) == 1)
                    {
                        continue;
                    }

                    cell.Terrain = TerrainType.Door;
                }
            }
        }
Exemple #20
0
        public Maze Generate(int width, int height, IRandomizer randomizer)
        {
            if (width < 3 || height < 3)
            {
                throw new ArgumentException("Minimal size of generated maze is 3x3");
            }

            _randomizer = randomizer;

            _cells = new MazeCellType[width, height];

            for (int x = 0; x < _cells.GetLength(0); x++)
            {
                for (int y = 0; y < _cells.GetLength(1); y++)
                {
                    _cells[x, y] = MazeCellType.Wall;
                }
            }

            int startX = _randomizer.GetRandomX(width - 2) + 1;
            int startY = _randomizer.GetRandomY(height - 2) + 1;

            _cells[startX, startY] = MazeCellType.Start;

            CarvePassages(startX, startY);

            return(Maze.Create(_cells));
        }
        /// <summary>
        /// Construct a neural genetic algorithm.
        /// </summary>
        ///
        /// <param name="network">The network to base this on.</param>
        /// <param name="randomizer">The randomizer used to create this initial population.</param>
        /// <param name="calculateScore">The score calculation object.</param>
        /// <param name="populationSize">The population size.</param>
        /// <param name="mutationPercent">The percent of offspring to mutate.</param>
        /// <param name="percentToMate">The percent of the population allowed to mate.</param>
        public NeuralGeneticAlgorithm(BasicNetwork network,
                                      IRandomizer randomizer, ICalculateScore calculateScore,
                                      int populationSize, double mutationPercent,
                                      double percentToMate) : base(TrainingImplementationType.Iterative)
        {
            Genetic = new NeuralGeneticAlgorithmHelper
            {
                CalculateScore = new GeneticScoreAdapter(calculateScore)
            };
            IPopulation population = new BasicPopulation(populationSize);

            Genetic.MutationPercent  = mutationPercent;
            Genetic.MatingPopulation = percentToMate * 2;
            Genetic.PercentToMate    = percentToMate;
            Genetic.Crossover        = new Splice(network.Structure.CalculateSize() / 3);
            Genetic.Mutate           = new MutatePerturb(4.0d);
            Genetic.Population       = population;
            for (int i = 0; i < population.PopulationSize; i++)
            {
                var chromosomeNetwork = (BasicNetwork)(network
                                                       .Clone());
                randomizer.Randomize(chromosomeNetwork);

                var genome = new NeuralGenome(chromosomeNetwork)
                {
                    GA = Genetic
                };
                Genetic.PerformCalculateScore(genome);
                Genetic.Population.Add(genome);
            }
            population.Sort();
        }
 /// <summary>Initializes a new instance of the <see cref="MutationGuarder"/> class.</summary>
 /// <param name="fixer">Handles generic resolution.</param>
 /// <param name="randomizer">Creates objects and populates them with random values.</param>
 /// <param name="duplicator">Deep clones objects.</param>
 /// <param name="asserter">Handles common test scenarios.</param>
 /// <param name="timeout">How long to wait for methods to complete.</param>
 internal MutationGuarder(GenericFixer fixer, IRandomizer randomizer,
                          IDuplicator duplicator, Asserter asserter, TimeSpan timeout)
     : base(fixer, randomizer, timeout)
 {
     _duplicator = duplicator ?? throw new ArgumentNullException(nameof(duplicator));
     _asserter   = asserter ?? throw new ArgumentNullException(nameof(asserter));
 }
Exemple #23
0
        public virtual void SetUp()
        {
            randomizer = Substitute.For <IRandomizer>();
            var cup = new Cup(2, randomizer);

            game = new Game(10, cup);
        }
 public override void Initialize()
 {
     InitializeWindowSize();
     Randomizer1 = new Randomizer();
     Engine      = new ParticleEngine(Randomizer1);
     base.Initialize();
 }
        public static TransportType GetRandomTransportTypeBetweenCarAndBus(IRandomizer randomizer)
        {
            var types = new[] { TransportType.Bus, TransportType.Car };
            var index = randomizer.GetRandomNumber(0, types.Length);

            return(types[index]);
        }
Exemple #26
0
        public void ProcessMap(Map <T> map, DungeonConfiguration configuration, IRandomizer randomizer)
        {
            var cellsToRemove = (int)(map.Width * map.Height * configuration.Sparseness);

            while (cellsToRemove != 0)
            {
                //Look at every cell in the maze grid. If the given cell contains a corridor that exits the cell in only one direction
                //"erase" that cell by removing the corridor
                var changedCells = new HashSet <T>();

                var deadEndCells = map.AllCells.Where(cell => cell.Sides.Values.Count(side => side) == 1).ToList();
                if (!deadEndCells.Any())
                {
                    break;
                }
                foreach (var deadEndCell in deadEndCells)
                {
                    deadEndCell.IsOpen = false;
                    var openDirection = deadEndCell.Sides.First(pair => pair.Value).Key;
                    deadEndCell.Sides[openDirection] = false;
                    var oppositeCell = map.GetAdjacentCell(deadEndCell, openDirection);
                    oppositeCell.Sides[openDirection.Opposite()] = false;
                    changedCells.Add(deadEndCell);
                    changedCells.Add(oppositeCell);
                    cellsToRemove--;
                    if (cellsToRemove == 0)
                    {
                        break;
                    }
                }
                //Repeat step #1 sparseness times
            }
        }
Exemple #27
0
        /// <summary>
        /// 난수발생기를 이용하여 <paramref name="values"/> 배열에 난수를 할당합니다.
        /// </summary>
        public static void FillValues(this IRandomizer randomizer, double[] values)
        {
            randomizer.ShouldNotBeNull("randomizer");
            values.ShouldNotBeEmpty("values");

            FillValues(randomizer, values, values.Length);
        }
Exemple #28
0
        protected CodeGeneratorBase(
            CodeGeneratorOptions options = null,
            IAlphabet alphabet           = null,
            IRandomizer randomizer       = null,
            IUniqueness uniqueness       = null,
            IStopWords stopWords         = null,
            ITransformer transformer     = null
            )
        {
            this.transformer = transformer;
            this.options     = options ?? new CodeGeneratorOptions();
            this.alphabet    = alphabet ?? new AsciiAlphabet();
            this.randomizer  = randomizer ?? new RandomRandomizer();
            this.uniqueness  = uniqueness ?? new NoUniqueness();
            this.stopWords   = stopWords ?? new NoStopWords();

            listeners = new object[]
            {
                this.alphabet,
                this.randomizer,
                this.uniqueness,
                this.stopWords
            }
            .Where(x => x is IListener)
            .Cast <IListener>()
            .ToList();
        }
Exemple #29
0
        /// <summary>
        /// Selects a random element of an enumerable.
        /// </summary>
        /// <typeparam name="T">The generic type of the enumerable.</typeparam>
        /// <param name="enumerable">The enumerable.</param>
        /// <param name="randomizer">The randomizer.</param>
        /// <returns>The randomly selected element.</returns>
        public static T SelectRandom <T>(this IEnumerable <T> enumerable, IRandomizer randomizer)
        {
            var list  = enumerable as IList <T> ?? enumerable.ToList();
            var index = randomizer.NextInt(0, list.Count);

            return(list[index]);
        }
Exemple #30
0
        public ErGraph(int n, double p, IRandomizer r)
        {
            throw new Exception("Deprecating this code, adding static factory methods to graph instead YN 9/10/17");
            this.N      = n;
            this.p      = p;
            this.random = r;

            for (int i = 1; i <= n; i++)
            {
                AddNode("n" + i);
            }

            var nodesList = _nodesDictionary.Values.ToList();

            for (int i = 0; i < nodesList.Count; i++)
            {
                for (int j = i + 1; j < nodesList.Count; j++)
                {
                    if (random.GetTrueWithProbability(p))
                    {
                        AddEdge(nodesList[i], nodesList[j]);
                    }
                }
            }
        }
Exemple #31
0
        public SpiceEvaluationContext(
            string name,
            SpiceExpressionMode mode,
            ISpiceNetlistCaseSensitivitySettings caseSetting,
            IRandomizer randomizer,
            IExpressionParserFactory expressionParserFactory,
            IExpressionFeaturesReader expressionFeaturesReader,
            IExpressionValueProvider expressionValueProvider,
            INameGenerator nameGenerator,
            IResultService resultService)

            : base(name,
                   caseSetting,
                   randomizer,
                   expressionParserFactory,
                   expressionFeaturesReader,
                   expressionValueProvider,
                   nameGenerator,
                   resultService)
        {
            Mode = mode;
            CreateCommonFunctions();
            CreateSpiceFunctions();
            CreateSpiceParameters();
        }
        public DroneSupervisor(Map map, IRandomizer randomizer)
        {
            _map = map;
            GoalValue = 0;

            for (var y = 0; y < map.Size; ++y)
                GoalValue += map[randomizer.Next(0, map.Size), y];
        }
Exemple #33
0
        // TODO: make it singleton and IDebugable

        public int Roll(int count, int diceSides, IRandomizer rnd)
        {
            int result = rnd.GetNext(count, diceSides * count + 1);

            //DoDebugLog(string.Format("Dice roll: {0}d{1} = {2}", count, diceSides, result));

            return result;
        }
Exemple #34
0
        /// <summary>
        /// Complete random roll of random count of random dice type
        /// </summary>
        /// <returns></returns>
        /// <remarks>There will be 1 to 9 rolled dices</remarks>
        public int Roll(IRandomizer rnd)
        {
            int dicesCount = rnd.GetNext(1, 10);
            string[] numDiceTypes = Enum.GetNames(typeof(Dices));
            int selectedDiceIndex = rnd.GetNext(numDiceTypes.Length);
            Dices selectedDice = (Dices)Enum.Parse(typeof(Dices), numDiceTypes[selectedDiceIndex]);

            return Roll(dicesCount, selectedDice, rnd);
        }
Exemple #35
0
        public Chip8Cpu(IDisplay display, IRandomizer randomizer, IKeyboard keyboard, IBcdConverter bcdConverter, IInstructionDecoder instructionDecoder, ITimerClock timerClock)
        {
            _display = display;
            _randomizer = randomizer;
            _keyboard = keyboard;
            _bcdConverter = bcdConverter;
            _instructionDecoder = instructionDecoder;
            _timerClock = timerClock;

            State = new CpuState();
        }
 public NeuralGeneticAlgorithm(BasicNetwork network, IRandomizer randomizer, ICalculateScore calculateScore, int populationSize, double mutationPercent, double percentToMate)
     : base(TrainingImplementationType.Iterative)
 {
     NeuralGeneticAlgorithmHelper helper;
     Label_012F:
     helper = new NeuralGeneticAlgorithmHelper();
     helper.CalculateScore = new GeneticScoreAdapter(calculateScore);
     this.Genetic = helper;
     IPopulation population = new BasicPopulation(populationSize);
     this.Genetic.MutationPercent = mutationPercent;
     this.Genetic.MatingPopulation = percentToMate * 2.0;
     this.Genetic.PercentToMate = percentToMate;
     this.Genetic.Crossover = new Splice(network.Structure.CalculateSize() / 3);
     this.Genetic.Mutate = new MutatePerturb(4.0);
     this.Genetic.Population = population;
     int num = 0;
     while (true)
     {
         NeuralGenome genome2;
         if (num < population.PopulationSize)
         {
             BasicNetwork network2 = (BasicNetwork) network.Clone();
             randomizer.Randomize(network2);
             if ((((uint) percentToMate) + ((uint) populationSize)) >= 0)
             {
                 genome2 = new NeuralGenome(network2) {
                     GA = this.Genetic
                 };
             }
         }
         else
         {
             population.Sort();
             if (((uint) populationSize) <= uint.MaxValue)
             {
                 return;
             }
             goto Label_012F;
         }
         if ((((uint) num) + ((uint) populationSize)) >= 0)
         {
             NeuralGenome g = genome2;
             this.Genetic.PerformCalculateScore(g);
             if (((uint) populationSize) > uint.MaxValue)
             {
                 goto Label_012F;
             }
             this.Genetic.Population.Add(g);
             num++;
         }
     }
 }
 /// <summary>
 /// Basic constructor
 /// </summary>
 /// <param name="network"></param>
 /// <param name="randomizer"></param>
 /// <param name="calculateScore"></param>
 public ParticleSwarmOptimizationAlgorithm(BasicNetwork network,IRandomizer randomizer, ICalculateScore calculateScore)
     : base(TrainingImplementationType.Iterative)
 {
 }
 public PEQTestApplication(IEventManager eventMgr, INodes nodes,
     IRandomizer randomizer, ILocation[] field)
 {
     Initialize(eventMgr, nodes, randomizer, field);
 }
 /*       / \
  *     // | \\
  *    /   |   \
  *        |           */
 public void Initialize(IEventManager eventMgr, INodes nodes,
     IRandomizer randomizer, ILocation[] field)
 {
     this.eventMgr = eventMgr;
     this.nodes = nodes;
     this.randomizer = randomizer;
     if (field is XYDoubleLocation[])
         this.field = (XYDoubleLocation[])field;
     else
     {
         isInitialized = false;
         return;
     }
     panelObjsHelper = new PanelObjHelper(panelObjs);
     this.eventSize = panelObjsHelper.GetDoubleByName("EventSize");
     this.eventMeanTime = panelObjsHelper.GetDoubleByName("EventMeanTime");
     this.eventFreq = panelObjsHelper.GetDoubleByName("EventFreq");
     this.numOccurances = panelObjsHelper.GetIntByName("NumOccurances");
     //this.finalEvent = panelObjsHelper.GetBoolByName("FinalEvent");
     isInitialized = true;
 }
 public void SetUp()
 {
     _sut = new Fluky.Framework.Randomizer();
 }
        public void Deploy()
        {
            if (!isInitialized)
                throw new InvalidOperationException("RandomDeployer not initialized!");

            List<XYDoubleLocation> pointList = new List<XYDoubleLocation>();

            rand = randFactory.CreateRandomizer();

            bool continueFlag;
            XYDoubleLocation initial, final, current;
            initial = (XYDoubleLocation)field[0];
            final = (XYDoubleLocation)field[1];
            current = new XYDoubleLocation();

            // Sink
            current = new XYDoubleLocation(final.X, (final.Y - initial.Y)/2);
            current.SetField(field);
            nodes.AddNode(nodeFactory.CreateNode(current));
            pointList.Add(current);
            nodes.GetNodeByID(0).IsSink = true;

            // Sources
            for (int i = 1; i < 6; i++)
            {
                current = new XYDoubleLocation(initial.X, (i-1)*(final.Y-initial.Y)/4);
                current.SetField(field);
                nodes.AddNode(nodeFactory.CreateNode(current));
                pointList.Add(current);
            }

            // Node Field
            for (int i = 6; i < numNodes; i++)
            {
                continueFlag = false;
                while (!continueFlag)
                {
                    continueFlag = true;
                    current = new XYDoubleLocation(
                        rand.NextDouble() * (final.X - initial.X - 2 * padding) + initial.X + padding,
                        rand.NextDouble() * (final.Y - initial.Y - 2 * padding) + initial.Y + padding);
                    foreach (XYDoubleLocation point in pointList)
                    {
                        if (current.Distance(point) < minDistance)
                            continueFlag = false;
                    }
                }
                pointList.Add(current);
                current.SetField(field);
                nodes.AddNode(nodeFactory.CreateNode(current));
            }
        }
        public void Initialize(IEventManager eventMgr, INodes nodes,
            IRandomizer randomizer, ILocation[] field)
        {
            panelObjsHelper = new PanelObjHelper(panelObjs);
            this.eventMgr = eventMgr;
            this.nodes = nodes;
            this.randomizer = randomizer;
            this.field = (XYDoubleLocation[])field;

            this.endTime = panelObjsHelper.GetDoubleByName("EndTime");
        }
 public Nodes(IRandomizer randomizer)
 {
     this.randomizer = randomizer;
 }
        /// <summary>
        /// Constructor. 
        /// </summary>
        /// <param name="network">an initialised Encog network. 
        ///                          The networks in the swarm will be created with 
        ///                          the same topology as this network.</param>
        /// <param name="randomizer">any type of Encog network weight initialisation
        ///                          object.</param>
        /// <param name="calculateScore">any type of Encog network scoring/fitness object.</param>
        /// <param name="populationSize">the swarm size.</param>
        public NeuralPSO(BasicNetwork network,
                IRandomizer randomizer, ICalculateScore calculateScore,
                int populationSize)
            : base(TrainingImplementationType.Iterative)
        {
            // initialisation of the member variables
            m_populationSize = populationSize;
            m_randomizer = randomizer;
            m_calculateScore = calculateScore;
            m_bestNetwork = network;

            m_networks = new BasicNetwork[m_populationSize];
            m_velocities = null;
            m_bestVectors = new double[m_populationSize][];
            m_bestErrors = new double[m_populationSize];
            m_bestVectorIndex = -1;

            // get a vector from the network.
            m_bestVector = NetworkCODEC.NetworkToArray(m_bestNetwork);

            m_va = new VectorAlgebra();
        }
 public FakeWeatherServiceProvider(IRandomizer randomizer)
 {
     _randomizer = randomizer;
 }
 public SimpleMemoryTrainer(IDictionaryStorage storage)
 {
     this.storage = storage;
     this.randomizer = new SimpleRandomizer (this.storage);
 }
Exemple #47
0
 public int Roll(string rollDesc, IRandomizer rnd)
 {
     return -1; // TODO: implement parser
 }
 public double EvaluateRandomizer(IRandomizer randomizer,
                                  BasicNetwork network, IMLDataSet training)
 {
     double total = 0;
     for (int i = 0; i < SAMPLE_SIZE; i++)
     {
         randomizer.Randomize(network);
         total += Evaluate(network, training);
     }
     return total/SAMPLE_SIZE;
 }
 public FQN_RandomDetectionEventGenerator(IEventManager eventMgr, INodes nodes,
     IRandomizer randomizer, ILocation[] field)
 {
     Initialize(eventMgr, nodes, randomizer, field);
 }
 private void InitBlock()
 {
     random = Esapi.Randomizer();
 }
Exemple #51
0
 //    /**
 //     * @return the logger
 //     */
 //    public static  ILogger getLogger() {
 //        if (Esapi.logger == null)
 //            return Logger();
 //        return Esapi.logger;
 //    }
 //
 //    /**
 //     * @param logger the logger to set
 //     */
 //    public static  void setLogger(ILogger logger) {
 //        Esapi.logger = logger;
 //    }
 //
 /// <summary>
 ///      The randomzier accessor.
 /// </summary>
 /// <returns> The randomizer implementation.
 /// </returns>
 public static IRandomizer Randomizer()
 {
     if (Esapi.randomizer == null)
         Esapi.randomizer = new Randomizer();
     return Esapi.randomizer;
 }
 public SimpleMemoryTrainer(IDictionaryStorage storage, IRandomizer randomizer)
 {
     this.storage = storage;
     this.randomizer = randomizer;
 }
Exemple #53
0
 public int Roll(int count, Dices dice, IRandomizer rnd)
 {
     return Roll(count, (int)dice, rnd);
 }
Exemple #54
0
 public void SetUp()
 {
     _sut = new Randomizer();
 }
Exemple #55
0
 public Board(IRandomizer randomizer)
 {
     _randomizer = randomizer;
 }