public StandardHandledTypeGenerator(IValueGenerator valueGenerator,
            CreateAccumulatorValueGeneratorDelegate getAccumulatorValueGenerator, Random random,
            int maxCollectionElementCount = 5)
        {
            StandardHandledTypeGenerator.Logger.Debug("Entering constructor");

            this.valueGenerator = valueGenerator;
            this.random = random;
            this.getAccumulatorValueGenerator = getAccumulatorValueGenerator;
            this.maxCollectionElementCount = maxCollectionElementCount;

            this.HandledTypeValueGetterDictionary = new Dictionary<Type, HandledTypeValueGetter>
            {
                {typeof (KeyValuePair<,>), this.GetKeyValuePair},
                {typeof (IDictionary<,>), this.GetDictionary},
                {typeof (Dictionary<,>), this.GetDictionary},
                {typeof (IEnumerable<>), this.GetList},
                {typeof (ICollection<>), this.GetList},
                {typeof (List<>), this.GetList},
                {typeof (IList<>), this.GetList},
                {typeof (Tuple<>), this.GetTuple },
                {typeof (Tuple<,>), this.GetTuple },
                {typeof (Tuple<,,>), this.GetTuple },
            };

            StandardHandledTypeGenerator.Logger.Debug("Exiting constructor");
        }
        public SingleValueGeneratorPool([NotNull] IValueGeneratorFactory factory, [NotNull] IProperty property)
        {
            Check.NotNull(factory, "factory");
            Check.NotNull(property, "property");

            _generator = factory.Create(property);
        }
        public StandardArrayRandomizer(Random random, IValueGenerator valueGenerator)
        {
            StandardArrayRandomizer.Logger.Debug("Entering constructor");

            this.random = random;
            this.valueGenerator = valueGenerator;

            StandardArrayRandomizer.Logger.Debug("Exiting constructor");
        }
Exemplo n.º 4
0
        private readonly ConcurrentDictionary <Type, object> _unconstrainedFactoryCache = new ConcurrentDictionary <Type, object>(); //new MemoryCache("constrained");

        public FakeChainFactory(
            CachedReturnValueGeneration cachedReturnValueGeneration,
            NestingLimit nestingLimit,
            ProxyGenerator proxyGenerator,
            IValueGenerator valueGenerator,
            ICollectionGenerator collectionGenerator)
        {
            _cachedReturnValueGeneration = cachedReturnValueGeneration;
            _nestingLimit        = nestingLimit;
            _proxyGenerator      = proxyGenerator;
            _valueGenerator      = valueGenerator;
            _collectionGenerator = collectionGenerator;
        }
Exemplo n.º 5
0
        private void IndexOfTest <T>(int testsCount, IValueGenerator <int> countGenerator, IValueGenerator <T> valueGenerator)
        {
            for (int iTest = 0; iTest < testsCount; iTest++)
            {
                var originalList = CreateOriginalList(countGenerator, valueGenerator);
                var testList     = CreateTestListByOriginal(originalList);

                foreach (var item in originalList)
                {
                    Assert.IsTrue(testList.IndexOf(item) == originalList.IndexOf(item));
                }
            }
        }
Exemplo n.º 6
0
        public static Matrix <T> Random(ICalculator <T> calc, int rows, int columns, IValueGenerator <T> rng)
        {
            var ts = new T[rows, columns];

            for (var row = 0; row < ts.GetLength(0); row++)
            {
                for (var col = 0; col < ts.GetLength(1); col++)
                {
                    ts[row, col] = rng.Next();
                }
            }
            return(new Matrix <T>(calc, ts));
        }
Exemplo n.º 7
0
        //Получаем генератор подходящего типа
        public IValueGenerator GetGenerator(Type valueType)
        {
            IValueGenerator resultGenerator = null;

            foreach (IValueGenerator generator in allGenerators)
            {
                if (generator.CanGenerate(valueType))
                {
                    resultGenerator = generator;
                }
            }
            return(resultGenerator);
        }
Exemplo n.º 8
0
        public static IValueGenerator Transform(this IValueGenerator gen, Func <float, float> func = null, bool vary = true)
        {
            Contract.Requires(gen != null);
            Contract.Ensures(Contract.Result <IValueGenerator>() != null);

            //If we're not transforming the value, and we're not making it unvarying this method has no effect!
            if (func == null && vary)
            {
                return(gen);
            }

            return(new WrapperValue(gen, func ?? (a => a), vary));
        }
Exemplo n.º 9
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="BuildCapability" /> class.
        /// </summary>
        /// <param name="generator">The generator that provides the build functions.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="generator" /> parameter is <c>null</c>.</exception>
        public BuildCapability(IValueGenerator generator)
        {
            generator = generator ?? throw new ArgumentNullException(nameof(generator));

            ImplementedByType = generator.GetType();
            SupportsCreate    = true;

            _createType      = (strategy, type, args) => generator.Generate(strategy, type);
            _createProperty  = (strategy, propertyInfo, args) => generator.Generate(strategy, propertyInfo);
            _createParameter = (strategy, parameterInfo, args) => generator.Generate(strategy, parameterInfo);
            _populate        = (strategy, instance) =>
                               throw new NotSupportedException(
                                         $"{nameof(IValueGenerator)} types do not support populating an instance.");
        }
Exemplo n.º 10
0
        public FloorRangeIncludeSpec(string id, IValueGenerator count, bool vary, bool continuous, KeyValuePair <float, KeyValuePair <string, string>[]>[] tags, IValueGenerator height)
        {
            Contract.Requires(count != null);
            Contract.Requires(tags != null);
            Contract.Requires(height != null);

            Continuous = continuous;
            Height     = height;
            Vary       = vary;

            _id    = id;
            _tags  = tags;
            _count = count;
        }
Exemplo n.º 11
0
        internal Parameter(double min, double max, bool logBase = false, int steps = 100)
        {
            Contract.Assert(max > min);
            Contract.Assert(steps > 0);
            Contract.Assert(!logBase || (logBase && min > 0));
            var option = new DoubleValueGenerator.Option()
            {
                Min     = min,
                Max     = max,
                Steps   = steps,
                LogBase = logBase,
            };

            this.ValueGenerator = new DoubleValueGenerator(option);
        }
Exemplo n.º 12
0
        private void RemoveTest <T>(int testsCount, IValueGenerator <int> countGenerator, IValueGenerator <T> valueGenerator)
        {
            for (int iTest = 0; iTest < testsCount; iTest++)
            {
                var originalList = CreateOriginalList(countGenerator, valueGenerator);
                var testList     = CreateTestListByOriginal(originalList);

                foreach (var item in originalList.ToArray())
                {
                    originalList.Remove(item);
                    testList.Remove(item);
                    Assert.IsTrue(originalList.SequenceEqual(testList));
                }
            }
        }
Exemplo n.º 13
0
        private void ClearTest <T>(int testsCount, IValueGenerator <int> countGenerator, IValueGenerator <T> valueGenerator)
        {
            for (int iTest = 0; iTest < testsCount; iTest++)
            {
                var testList = new CommandedList <T>(CreateCommandDispatcher());
                var count    = countGenerator.Generate();
                for (int i = 0; i < count; i++)
                {
                    testList.Add(valueGenerator.Generate());
                }
                testList.Clear();

                Assert.IsFalse(testList.Any());
            }
        }
Exemplo n.º 14
0
        public WallGrowthParameters(IValueGenerator seedDistance, IValueGenerator seedChance, IValueGenerator parallelLengthMultiplier, IValueGenerator parallelCheckWidth, IValueGenerator parallelAngleThreshold, IValueGenerator intersectionContinuationChance)
        {
            Contract.Requires(seedDistance != null);
            Contract.Requires(seedChance != null);
            Contract.Requires(parallelLengthMultiplier != null);
            Contract.Requires(parallelCheckWidth != null);
            Contract.Requires(parallelAngleThreshold != null);
            Contract.Requires(intersectionContinuationChance != null);

            _seedDistance                   = seedDistance;
            _seedChance                     = seedChance;
            _parallelLengthMultiplier       = parallelLengthMultiplier;
            _parallelCheckWidth             = parallelCheckWidth;
            _parallelAngleThreshold         = parallelAngleThreshold;
            _intersectionContinuationChance = intersectionContinuationChance;
        }
Exemplo n.º 15
0
        private void RemoveAtTest <T>(int testsCount, IValueGenerator <int> countGenerator, IValueGenerator <T> valueGenerator, Int32Generator indexGenerator)
        {
            for (int iTest = 0; iTest < testsCount; iTest++)
            {
                var originalList = CreateOriginalList(countGenerator, valueGenerator);
                var testList     = CreateTestListByOriginal(originalList);

                while (originalList.Any())
                {
                    var index = indexGenerator.Generate(0, originalList.Count);
                    originalList.RemoveAt(index);
                    testList.RemoveAt(index);
                    Assert.IsTrue(originalList.SequenceEqual(testList));
                }
            }
        }
        //Todo Criteria so machen dass man die gewichtung nur einmal für alle ändern muss
        /// <summary>
        /// returns p count of  Entries with 4 Criteria. The values of the Criteria are uniformly distributed(random).
        /// </summary>
        /// <param name="p">how many entries to generate</param>
        /// <returns>entries generated by random</returns>
        public static List <Participant> DummyEntries(IValueGenerator valueGenerator, int p, int numHet, int dimHet, int numHom, int dimHom, IRule _rule = null)
        {
            List <Participant> loEntries = new List <Participant>();

            List <float>[] values = new List <float> [(numHet * dimHet) + (numHom * dimHom)]; // store values here
            for (int i = 0; i < (numHet * dimHet) + (numHom * dimHom); i++)
            {
                // generate values for one specific dimension of a criterion for p players
                values[i] = valueGenerator.GenerateValues(0, 1, p);
            }

            for (int i = 0; i < p; i++)
            {
                System.Console.Out.WriteLine("Generating participant " + i + "..");
                List <Criterion> loCriteria = new List <Criterion>();
                //pseudoCriteria
                for (int j = 1; j <= numHet; j++)
                {
                    SpecificCriterion c = new Criteria.SpecificCriterion("Khet" + j, dimHet, 0, 1, false, 1);
                    loCriteria.Add(c);
                    for (int k = 1; k <= dimHet; k++)
                    {
                        c.Value[k - 1] = values[(j * k) - 1][i];
                    }
                }
                for (int j = 1; j <= numHom; j++)
                {
                    SpecificCriterion c = new Criteria.SpecificCriterion("Khom" + j, dimHom, 0, 1, true, 1);
                    loCriteria.Add(c);
                    for (int k = 1; k <= dimHom; k++)
                    {
                        c.Value[k - 1] = values[((numHet * dimHet) + j * k) - 1][i];
                    }
                }
                Participant participant = new Participant(loCriteria);
                loEntries.Add(participant);
            }

            if (_rule != null)
            {
                foreach (Participant part in loEntries)
                {
                    _rule.AdjustParticipant(part);
                }
            }
            return(loEntries);
        }
Exemplo n.º 17
0
        private void AddTest <T>(int testsCount, IValueGenerator <int> countGenerator, IValueGenerator <T> valueGenerator)
        {
            for (int iTest = 0; iTest < testsCount; iTest++)
            {
                var originalList = new List <T>();
                var testList     = new CommandedList <T>(CreateCommandDispatcher());

                var count = countGenerator.Generate();
                for (int i = 0; i < count; i++)
                {
                    var value = valueGenerator.Generate();
                    originalList.Add(value);
                    testList.Add(value);
                    Assert.IsTrue(originalList.SequenceEqual(testList));
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// <para>Заполнить массив значениями</para>
        /// </summary>
        /// <typeparam name="T">Тип элементов массива</typeparam>
        /// <param name="array">Заполняемый массив</param>
        /// <param name="generator">Генератор значений</param>
        /// <param name="start">Первый элемент массива, с которого начинается заполнение</param>
        /// <param name="count">Количество элементов массива, заменяемых новым значением</param>
        /// <remarks>v.2021.04.18</remarks>
        public static void Fill <T>(this T[] array, IValueGenerator <T> generator, long start = 0, long count = 0)
        {
            #region Check arguments
#if CHECK_ARGS
            _ = array ?? throw new ArgumentNullException(nameof(array));
            _ = generator ?? throw new ArgumentNullException(nameof(generator));

            if ((count < 0) || (count > array.Length))
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            if ((start < 0) || ((start + count) > array.Length))
            {
                throw new ArgumentOutOfRangeException(nameof(start));
            }

            /*
             #else
             *
             *          if ((array is null) ||
             *              (generator is null) ||
             *              (count < 0) || (count > array.Length) ||
             *              (start < 0) || ((start + count) > array.Length))
             *          {
             *              Debug.WriteLine("incorrect call {0}<{1}>(array:{2},generator:{3},start:{4},count:{5})",
             *                  "Darkangel.Arrays.ArrayHelper.Fill",
             *                  typeof(T).FullName,
             *                  (array is null) ? "null" : array.Length.ToString(),
             *                  generator.GetType().FullName,
             *                  start,
             *                  count
             *                  );
             *              return;
             *          }
             */
#endif
            #endregion Check arguments

            var end = (count == 0) ? (array.Length) : (start + count);

            for (var i = start; i < end; i++)
            {
                array[i] = generator.Generate(i);
            }
        }
Exemplo n.º 19
0
        // Генерация значения. Если нет подходящего генератора, то генерируется дефолтное значение (0 или null)
        public object GenerateValue(GeneratorContext context)
        {
            IValueGenerator generator = GetGenerator(context.TargetType);
            object          value;

            if (generator != null)
            {
                value = generator.Generate(context);
            }
            else
            {
                value = GetDefaultValue(context.TargetType);
                Console.WriteLine("Dont have generator for " + context.TargetType.Name);
            }

            return(value);
        }
        public ParticipantGenerator(int numberOfEntriesToGenerate, int numhet, int dimhet, int numhom, int dimhom, IValueGenerator valueGenerator, IRule aRuel, IParticipantReaderWriter methodHowToWriteEntriesOut, string filename)
        {
            ruel   = aRuel;
            writer = methodHowToWriteEntriesOut;
            this.valueGenerator = valueGenerator;
            //create list of entries with random values between 0 and 1
            loParticipants = DummyEntries(valueGenerator, numberOfEntriesToGenerate, numhet, dimhet, numhom, dimhom);

            //adjust entries by using ruel e.g. DefaultRuel map value form 0-1 to minValue-maxvalue array
            foreach (Participant e in loParticipants)
            {
                ruel.AdjustParticipant(e);
            }


            //write them to an XML/textfile
            writer.WriteParticipantsToFile(loParticipants, filename);
        }
Exemplo n.º 21
0
        public TracingConfiguration(BaseScalarField priorityField, BaseScalarField separationField, ITensorField tensorField, IValueGenerator roadWidth,
                                    float searchAngle   = 0.3926991f, //22.5 degrees in radians
                                    float segmentLength = 10,
                                    float mergeDistance = 25
                                    )
        {
            Contract.Requires(priorityField != null);
            Contract.Requires(separationField != null);
            Contract.Requires(tensorField != null);
            Contract.Requires(roadWidth != null);

            _priorityField          = priorityField;
            _separationField        = separationField;
            _tensorField            = tensorField;
            _roadWidth              = roadWidth;
            _consineSearchConeAngle = (float)Math.Cos(searchAngle);
            _segmentLength          = segmentLength;
            _mergeDistance          = mergeDistance;
        }
Exemplo n.º 22
0
        private void ContainsTest <T>(int testsCount, IValueGenerator <int> countGenerator, IValueGenerator <T> valueGenerator)
        {
            for (int iTest = 0; iTest < testsCount; iTest++)
            {
                var originalList = CreateOriginalList(countGenerator, valueGenerator);
                var testList     = CreateTestListByOriginal(originalList);

                foreach (var item in originalList)
                {
                    Assert.IsTrue(originalList.Contains(item) == testList.Contains(item));
                }

                var count = countGenerator.Generate();
                for (int i = 0; i < count; i++)
                {
                    var value = valueGenerator.Generate();
                    Assert.IsTrue(originalList.Contains(value) == testList.Contains(value));
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="outline">Polygon outline of this map (clockwise wound, potentially concave)</param>
        /// <param name="internalRooms">Set of rooms which must be included unchanged in this map</param>
        /// <param name="random">PRNG (0-1)</param>
        /// <param name="metadata">Metadata used in random generation</param>
        /// <param name="parameters"></param>
        public GrowthMap(IReadOnlyList <Vector2> outline, IReadOnlyList <IReadOnlyList <Vector2> > internalRooms, Func <double> random, INamedDataCollection metadata, WallGrowthParameters parameters)
        {
            Contract.Requires(outline != null);
            Contract.Requires(internalRooms != null);
            Contract.Requires(random != null);
            Contract.Requires(metadata != null);
            Contract.Requires(parameters != null);

            _outline       = outline;
            _internalRooms = internalRooms;
            _random        = random;
            _metadata      = metadata;

            _seedDistance                   = parameters.SeedDistance;
            _seedChance                     = parameters.SeedChance;
            _parallelLengthMultiplier       = parameters.ParallelLengthMultiplier;
            _parallelCheckWidth             = parameters.ParallelCheckWidth;
            _cosineParallelAngleThreshold   = parameters.ParallelAngleThreshold.Transform(a => (float)Math.Cos(a));
            _intersectionContinuationChance = parameters.IntersectionContinuationChance;

            var bounds = BoundingRectangle.CreateFromPoints(outline).Inflate(0.2f);

            _mesh = new Mesh <FloorplanVertexTag, FloorplanHalfEdgeTag, FloorplanFaceTag>(bounds);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Computes a single-mutation neighborhood (one parameter at a time) for a given configuration. For
        /// numeric parameters, samples K mutations (i.e., creates K neighbors based on that parameter).
        /// </summary>
        /// <param name="parent">Starting configuration.</param>
        /// <returns>A set of configurations that each differ from parent in exactly one parameter.</returns>
        private ParameterSet[] GetOneMutationNeighborhood(ParameterSet parent)
        {
            List <ParameterSet>     neighbors = new List <ParameterSet>();
            SweeperProbabilityUtils spu       = new SweeperProbabilityUtils();

            for (int i = 0; i < _sweepParameters.Length; i++)
            {
                // This allows us to query possible values of this parameter.
                IValueGenerator sweepParam = _sweepParameters[i];

                // This holds the actual value for this parameter, chosen in this parameter set.
                IParameterValue pset = parent[sweepParam.Name];

                Runtime.Contracts.Assert(pset != null);

                DiscreteValueGenerator parameterDiscrete = sweepParam as DiscreteValueGenerator;
                if (parameterDiscrete != null)
                {
                    // Create one neighbor for every discrete parameter.
                    Float[] neighbor = SweeperProbabilityUtils.ParameterSetAsFloatArray(_sweepParameters, parent, false);

                    int hotIndex = -1;
                    for (int j = 0; j < parameterDiscrete.Count; j++)
                    {
                        if (parameterDiscrete[j].Equals(pset))
                        {
                            hotIndex = j;
                            break;
                        }
                    }

                    Runtime.Contracts.Assert(hotIndex >= 0);

                    Random r           = new Random();
                    int    randomIndex = r.Next(0, parameterDiscrete.Count - 1);
                    randomIndex += randomIndex >= hotIndex ? 1 : 0;
                    neighbor[i]  = randomIndex;
                    neighbors.Add(SweeperProbabilityUtils.FloatArrayAsParameterSet(_sweepParameters, neighbor, false));
                }
                else
                {
                    INumericValueGenerator parameterNumeric = sweepParam as INumericValueGenerator;
                    Runtime.Contracts.Assert(parameterNumeric != null, "SMAC sweeper can only sweep over discrete and numeric parameters");

                    // Create k neighbors (typically 4) for every numerical parameter.
                    for (int j = 0; j < _args.NumNeighborsForNumericalParams; j++)
                    {
                        Float[] neigh  = SweeperProbabilityUtils.ParameterSetAsFloatArray(_sweepParameters, parent, false);
                        double  newVal = spu.NormalRVs(1, neigh[i], 0.2)[0];
                        while (newVal <= 0.0 || newVal >= 1.0)
                        {
                            newVal = spu.NormalRVs(1, neigh[i], 0.2)[0];
                        }
                        neigh[i] = (Float)newVal;
                        ParameterSet neighbor = SweeperProbabilityUtils.FloatArrayAsParameterSet(_sweepParameters, neigh, false);
                        neighbors.Add(neighbor);
                    }
                }
            }
            return(neighbors.ToArray());
        }
 public UniqueValueTypeGenerator(GetAccumulatorValueGenerator getAccumulatorValueGenerator, IValueGenerator valueGenerator,
     IHandledTypeGenerator handledTypeGenerator)
     : base(valueGenerator, handledTypeGenerator)
 {
     this.accumulatorValueGenerator = getAccumulatorValueGenerator(this);
 }
 protected BaseValueGeneratorContracts(IValueGenerator min, IValueGenerator max)
     : base(min, max)
 {
 }
Exemplo n.º 27
0
        /// <summary>
        /// Generic parameter parser. Currently hand-hacked to auto-detect type.
        ///
        /// Generic form:   Name:Values
        /// for example,    lr:0.05-0.4
        ///          lambda:0.1-1000@log10
        ///          nl:2-64@log2
        ///          norm:-,+
        /// </summary>
        /// REVIEW: allow overriding auto-detection to specify type
        /// and delegate to parameter type for actual parsing
        /// REVIEW: specifying ordinal discrete parameters
        public bool TryParseParameter(string paramValue, Type paramType, string paramName, out IValueGenerator sweepValues, out string error)
        {
            sweepValues = null;
            error       = null;

            if (paramValue.Contains(','))
            {
                var generatorArgs = new DiscreteParamArguments();
                generatorArgs.Name   = paramName;
                generatorArgs.Values = paramValue.Split(',');
                sweepValues          = new DiscreteValueGenerator(generatorArgs);
                return(true);
            }

            // numeric parameter
            if (!CmdParser.IsNumericType(paramType))
            {
                return(false);
            }

            // REVIEW:  deal with negative bounds
            string scaleStr = null;
            int    atIdx    = paramValue.IndexOf('@');

            if (atIdx < 0)
            {
                atIdx = paramValue.IndexOf(';');
            }
            if (atIdx >= 0)
            {
                scaleStr   = paramValue.Substring(atIdx + 1);
                paramValue = paramValue.Substring(0, atIdx);
                if (scaleStr.Length < 1)
                {
                    error = $"Could not parse sweep range for parameter: {paramName}";
                    return(false);
                }
            }

            // Extract the minimum, and the maximum value of the list of suggested sweeps.
            // Positive lookahead splitting at the '-' character.
            // It is used for the Float and Long param types.
            // Example format: "0.02-0.1;steps:5".
            string[] minMaxRegex = Regex.Split(paramValue, "(?<=[^eE])-");
            if (minMaxRegex.Length != 2)
            {
                if (minMaxRegex.Length > 2)
                {
                    error = $"Could not parse sweep range for parameter: {paramName}";
                }

                return(false);
            }
            string minStr = minMaxRegex[0];
            string maxStr = minMaxRegex[1];

            int    numSteps = 100;
            Double stepSize = -1;
            bool   logBase  = false;

            if (scaleStr != null)
            {
                try
                {
                    string[] options          = scaleStr.Split(';');
                    bool[]   optionsSpecified = new bool[3];
                    foreach (string option in options)
                    {
                        if (option.StartsWith("log") && !option.StartsWith("log-") && !option.StartsWith("log:-"))
                        {
                            logBase             = true;
                            optionsSpecified[0] = true;
                        }
                        if (option.StartsWith("steps"))
                        {
                            numSteps            = int.Parse(option.Substring(option.IndexOf(':') + 1));
                            optionsSpecified[1] = true;
                        }
                        if (option.StartsWith("inc"))
                        {
                            stepSize            = Double.Parse(option.Substring(option.IndexOf(':') + 1), CultureInfo.InvariantCulture);
                            optionsSpecified[2] = true;
                        }
                    }
                    if (options.Length != optionsSpecified.Count(b => b))
                    {
                        error = $"Could not parse sweep range for parameter: {paramName}";
                        return(false);
                    }
                }
                catch (Exception e)
                {
                    error = $"Error creating sweep generator for parameter '{paramName}': {e.Message}";
                    return(false);
                }
            }

            if (paramType == typeof(UInt16) ||
                paramType == typeof(UInt32) ||
                paramType == typeof(UInt64) ||
                paramType == typeof(short) ||
                paramType == typeof(int) ||
                paramType == typeof(long))
            {
                long min;
                long max;
                if (!long.TryParse(minStr, out min) || !long.TryParse(maxStr, out max))
                {
                    return(false);
                }
                var generatorArgs = new Microsoft.ML.Sweeper.LongParamArguments();
                generatorArgs.Name     = paramName;
                generatorArgs.Min      = min;
                generatorArgs.Max      = max;
                generatorArgs.NumSteps = numSteps;
                generatorArgs.StepSize = (stepSize > 0 ? stepSize : new Nullable <Double>());
                generatorArgs.LogBase  = logBase;

                try
                {
                    sweepValues = new LongValueGenerator(generatorArgs);
                }
                catch (Exception e)
                {
                    error = $"Error creating sweep generator for parameter '{paramName}': {e.Message}";
                    return(false);
                }
            }
            else
            {
                Float minF;
                Float maxF;
                if (!Float.TryParse(minStr, out minF) || !Float.TryParse(maxStr, out maxF))
                {
                    return(false);
                }
                var floatArgs = new FloatParamArguments();
                floatArgs.Name     = paramName;
                floatArgs.Min      = minF;
                floatArgs.Max      = maxF;
                floatArgs.NumSteps = numSteps;
                floatArgs.StepSize = (stepSize > 0 ? stepSize : new Nullable <Double>());
                floatArgs.LogBase  = logBase;

                try
                {
                    sweepValues = new FloatValueGenerator(floatArgs);
                }
                catch (Exception e)
                {
                    error = $"Error creating sweep generator for parameter '{paramName}': {e.Message}";
                    return(false);
                }
            }
            return(true);
        }
 public GameManager(IEventListData eventListData, IValueGenerator valueGenerator)
 {
     _eventListData = eventListData;
     _valueGenerator = valueGenerator;
     InitGame();
 }
Exemplo n.º 29
0
 public Bevel(IValueGenerator angle, IValueGenerator distance)
 {
     _angle    = angle;
     _distance = distance;
 }
Exemplo n.º 30
0
        private object FillObject(object obj)
        {
            if (obj != null)
            {
                FieldInfo[]    Fields     = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
                PropertyInfo[] Properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (FieldInfo field in Fields)
                {
                    if (IsValueSet(field, obj))
                    {
                        ConfigurationRule configurationRule = null;
                        if (Configuration != null)
                        {
                            foreach (ConfigurationRule Rule in Configuration.ConfigurationRules)
                            {
                                if ((Rule.FieldName == field.Name) && (Rule.FieldType == field.FieldType))
                                {
                                    configurationRule = Rule;
                                }
                            }
                        }
                        if (configurationRule == null)
                        {
                            field.SetValue(obj, Create(field.FieldType));
                        }
                        else
                        {
                            int              seed    = (int)DateTime.Now.Ticks & 0x0000FFFF;
                            Faker            faker   = new Faker(Configuration);
                            GeneratorContext Context = new GeneratorContext(new Random(seed), field.FieldType, faker);
                            IValueGenerator  test    = (IValueGenerator)Activator.CreateInstance(configurationRule.GeneratorName);
                            field.SetValue(obj, ((IValueGenerator)Activator.CreateInstance(configurationRule.GeneratorName)).Generate(Context));
                        }
                    }
                }

                foreach (PropertyInfo property in Properties)
                {
                    if ((property.CanWrite) && (IsValueSet(property, obj)))
                    {
                        ConfigurationRule configurationRule = null;
                        if (Configuration != null)
                        {
                            foreach (ConfigurationRule Rule in Configuration.ConfigurationRules)
                            {
                                if ((Rule.FieldName == property.Name) && (Rule.FieldType == property.PropertyType))
                                {
                                    configurationRule = Rule;
                                }
                            }
                        }
                        if (configurationRule == null)
                        {
                            property.SetValue(obj, Create(property.PropertyType));
                        }
                        else
                        {
                            int              seed    = (int)DateTime.Now.Ticks & 0x0000FFFF;
                            Faker            faker   = new Faker(Configuration);
                            GeneratorContext Context = new GeneratorContext(new Random(seed), property.PropertyType, faker);
                            IValueGenerator  test    = (IValueGenerator)Activator.CreateInstance(configurationRule.GeneratorName);
                            property.SetValue(obj, ((IValueGenerator)Activator.CreateInstance(configurationRule.GeneratorName)).Generate(Context));
                        }
                    }
                }
            }
            return(obj);
        }
Exemplo n.º 31
0
 public FakeSpecialCase(IValueGenerator valueGenerator)
 {
     _valueGenerator = valueGenerator;
 }
Exemplo n.º 32
0
 private MergingParameters(IValueGenerator angularWeight, IValueGenerator angularThreshold, IValueGenerator convexWeight, IValueGenerator convexThreshold, IValueGenerator areaWeight, IValueGenerator areaThreshold, IValueGenerator areaCutoff)
 {
     AngularWeight    = angularWeight;
     AngularThreshold = angularThreshold;
     ConvexWeight     = convexWeight;
     ConvexThreshold  = convexThreshold;
     AreaWeight       = areaWeight;
     AreaThreshold    = areaThreshold;
     AreaCutoff       = areaCutoff;
 }
Exemplo n.º 33
0
 public CorridorParameters(IValueGenerator width)
 {
     Width = width;
 }
 public GameManager(IEventListData eventListData, IValueGenerator valueGenerator)
 {
     _eventListData  = eventListData;
     _valueGenerator = valueGenerator;
     InitGame();
 }
Exemplo n.º 35
0
 public DoubleUniqueGenerator(IValueGenerator <double> baseGenerator, DoubleComparer comparer)
     : base(baseGenerator)
 {
     Comparer = comparer ?? throw new NullReferenceException(nameof(comparer));
 }