示例#1
0
        public static List <Piece> GeneratePieces()
        {
            List <Piece> pieces = new List <Piece>();

            var pieceCoordinates = Utils.GeneratePiecesCoordinates(NumberOfPiecesDist.Sample());
            var kingsCoordinates = Utils.GenerateKingCoordinates(pieceCoordinates);

            pieces.Add(new Piece(kingsCoordinates[0], Type.King, Color.White));
            pieces.Add(new Piece(kingsCoordinates[1], Type.King, Color.Black));

            foreach (var coordinate in pieceCoordinates)
            {
                if (coordinate.Y == 0 || coordinate.Y == 7)
                {
                    pieces.Add(new Piece(
                                   coordinate,
                                   Generator.GenerateNotPawnPiece(NotPawnPiecesDist.Sample()),
                                   Generator.GenerateColor(ColorDist.Sample())));
                }
                else
                {
                    pieces.Add(new Piece(
                                   coordinate,
                                   Generator.GeneratePiece(AllPiecesDist.Sample()),
                                   Generator.GenerateColor(ColorDist.Sample())));
                }
            }

            return(pieces);
        }
示例#2
0
        private Order[] CancellationOrdersByValue(EquityInstrumentIntraDayTimeBar security, int totalOrders)
        {
            if (totalOrders == 0 || security == null) return new Order[0];

            var ordersToCancel = DiscreteUniform.Sample(1, totalOrders);
            var ordersToFulfill = totalOrders - ordersToCancel;

            // ReSharper disable RedundantCast
            var minimumPerOrderValue =
                (int)((decimal)this._valueOfCancelledTradeThreshold * (decimal)(1m / ordersToCancel) + 1);

            // ReSharper restore RedundantCast
            var orders = new List<Order>();

            for (var x = 0; x < ordersToCancel; x++)
                orders.Add(
                    this.OrderForValue(
                        OrderStatus.Cancelled,
                        minimumPerOrderValue,
                        security,
                        this._lastFrame.Exchange));

            for (var x = 0; x < ordersToFulfill; x++)
            {
                var fulfilledOrderValue = DiscreteUniform.Sample(0, minimumPerOrderValue * 3);
                orders.Add(
                    this.OrderForValue(OrderStatus.Filled, fulfilledOrderValue, security, this._lastFrame.Exchange));
            }

            return orders.ToArray();
        }
示例#3
0
        /// <summary>
        ///     BeInfluenced a beliefBit by doing
        ///     Random value is used to set the new value
        /// </summary>
        /// <param name="model"></param>
        /// <param name="beliefBit"></param>
        public void Learn(RandomGenerator model, byte beliefBit)
        {
            var bit = BeliefBits.GetBit(beliefBit);

            switch (model)
            {
            case RandomGenerator.RandomUniform:
                bit += ContinuousUniform.Sample(RangeMin, RangeMax);
                if (bit < RangeMin)
                {
                    bit = RangeMin;
                }

                if (bit > RangeMax)
                {
                    bit = RangeMax;
                }

                break;

            case RandomGenerator.RandomBinary:
                bit = DiscreteUniform.Sample(RangeMin, RangeMax);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(model), model, null);
            }

            BeliefBits.SetBit(beliefBit, bit);
        }
        private OrderDirections CalculateTradeDirection()
        {
            var buyOrSellSample = DiscreteUniform.Sample(1, 2);
            var buyOrSell       = (OrderDirections)buyOrSellSample;

            return(buyOrSell);
        }
        private OrderStatus CalculateOrderStatus()
        {
            var orderStatusSample = DiscreteUniform.Sample(1, 5);
            var orderStatus       = (OrderStatus)orderStatusSample;

            return(orderStatus);
        }
示例#6
0
        private static AtomType IntegralType(string name, int lower, int upper, string suffix = "")
        {
            Func <Random, string> provider =
                random => DiscreteUniform.Sample(random, lower, upper).ToString() + suffix;

            return(new AtomType(name, false, provider));
        }
        private void TradeOnHeartbeat(object sender, EventArgs e)
        {
            lock (this._lock)
            {
                if (this._lastFrame == null || !this._lastFrame.Securities.Any())
                {
                    return;
                }

                var selectSecurityToSpoof = DiscreteUniform.Sample(0, this._lastFrame.Securities.Count - 1);
                var spoofSecurity         = this._lastFrame.Securities.Skip(selectSecurityToSpoof).FirstOrDefault();

                // limited to six as recursion > 8 deep tends to get tough on the stack and raise the risk of a SO error
                // if you want to increase this beyond 20 update spoofed order code for volume as well.
                var spoofSize     = DiscreteUniform.Sample(1, 6);
                var spoofedOrders = this.SpoofedOrder(spoofSecurity, spoofSize, spoofSize)
                                    .OrderBy(x => x.MostRecentDateEvent());
                var counterTrade = this.CounterTrade(spoofSecurity);

                foreach (var item in spoofedOrders)
                {
                    this.TradeStream.Add(item);
                }

                this.TradeStream.Add(counterTrade);
            }
        }
示例#8
0
 /// <summary>
 /// Sets this instance's AmiabilityLevel
 /// </summary>
 /// <param name="seed">Seed based on player and slice</param>
 private void SetLevel(int seed)
 {
     uniformRandSeed  = new SystemRandomSource(seed);
     binomialRandSeed = new SystemRandomSource(seed);   // Doesn't matter if it's the same seed
     uniformDist      = new DiscreteUniform(0, Enum.GetNames(typeof(AmiabilityLevel)).Length - 1, uniformRandSeed);
     AmiabilityLevel  = (AmiabilityLevel)uniformDist.Sample();
 }
示例#9
0
        public static IEnumerable <TSLProtocol> GetDefaultNumberOfDistinctProtocols(this TSLGeneratorContext context)
        {
            var protocolNumber = DiscreteUniform.Sample(context.MasterRandom,
                                                        CommunicationInstanceSettings.MinProtocolNumber, CommunicationInstanceSettings.MaxProtocolNumber);

            return(context.GetRandomDistinctProtocols(protocolNumber));
        }
示例#10
0
        private void SetAgentKnowledge(CognitiveAgent actor, IReadOnlyList <IAgentId> knowledgeIds, int i)
        {
            var index = 0;

            switch (ExampleMainOrganization.Knowledge)
            {
            case 0:
                // same Knowledge for all
                index = 0;
                break;

            case 1:
                // Knowledge is by group
                index = i;
                break;

            case 2:
                // Knowledge is randomly defined for agentId
                index = DiscreteUniform.Sample(0, ExampleMainOrganization.GroupsCount - 1);
                break;
            }

            actor.KnowledgeModel.AddKnowledge(knowledgeIds[index], ExampleMainOrganization.KnowledgeLevel,
                                              actor.Cognitive.InternalCharacteristics.MinimumRemainingKnowledge,
                                              actor.Cognitive.InternalCharacteristics.TimeToLive);
        }
        private Order[] SpoofedOrder(
            EquityInstrumentIntraDayTimeBar security,
            int remainingSpoofedOrders,
            int totalSpoofedOrders)
        {
            if (security == null || remainingSpoofedOrders <= 0)
            {
                return(new Order[0]);
            }

            var priceOffset     = (100 + remainingSpoofedOrders) / 100m;
            var limitPriceValue = security.SpreadTimeBar.Bid.Value * priceOffset;
            var limitPrice      = new Money(limitPriceValue, security.SpreadTimeBar.Bid.Currency);

            var individualTradeVolumeLimit = 100 / totalSpoofedOrders;
            var volumeTarget = (100 + DiscreteUniform.Sample(0, individualTradeVolumeLimit)) / 100m;
            var volume       = (int)(security.SpreadTimeBar.Volume.Traded * volumeTarget);

            var statusChangedOn = DateTime.UtcNow.AddMinutes(-10 + remainingSpoofedOrders);
            var tradePlacedOn   = statusChangedOn;

            var spoofedTrade = new Order(
                security.Security,
                security.Market,
                null,
                Guid.NewGuid().ToString(),
                DateTime.UtcNow,
                "order-v1",
                "order-v1",
                "order-group-1",
                tradePlacedOn,
                tradePlacedOn,
                null,
                null,
                statusChangedOn,
                null,
                OrderTypes.LIMIT,
                OrderDirections.BUY,
                security.SpreadTimeBar.Price.Currency,
                security.SpreadTimeBar.Price.Currency,
                OrderCleanDirty.NONE,
                null,
                limitPrice,
                limitPrice,
                volume,
                volume,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                OptionEuropeanAmerican.NONE,
                new DealerOrder[0]);

            return(new[] { spoofedTrade }
                   .Concat(this.SpoofedOrder(security, remainingSpoofedOrders - 1, totalSpoofedOrders)).ToArray());
        }
示例#12
0
        protected void WaitForTransmit(bool failed)
        {
            backoff = failed ? Math.Min(backoff * 2 + 1, Constants.CW_MAX) : Constants.CW_MIN;
            int sample = DiscreteUniform.Sample(0, backoff);

            timeToWait   = Constants.SIFS_TIME + sample * Constants.SLOT_TIME;
            isWaitingAck = false;
        }
        private int CalculateVolume(EquityInstrumentIntraDayTimeBar tick)
        {
            var upperLimit    = Math.Max(tick.SpreadTimeBar.Volume.Traded, 1);
            var tradingVolume = (int)Math.Sqrt(upperLimit);
            var volume        = DiscreteUniform.Sample(1, tradingVolume);

            return(volume);
        }
示例#14
0
        private string GetRandomListValue(Random random)
        {
            var count = DiscreteUniform.Sample(random,
                                               0, ContainerProbabilities.List.MaxRandomElementCount);
            var elems = Enumerable.Range(0, count).Select(_ => ElementType.GetRandomValue(random));

            return($"new {Name}{{ {string.Join(", ", elems)} }}");
        }
示例#15
0
        public Room GenerateRoom()
        {
            var width  = sizeGen.Sample();
            var height = sizeGen.Sample();

            var offset = new DiscreteUniform(1, height - 2).Sample();

            var pivot = lastRoom.ExitPoint + new Point(1, -offset);

            var room = GenerateEmpty(width, height, pivot, lastRoom.ExitPoint, !first);

            var characterGen = new CharacterGenerator();
            var itemGen      = new ItemGenerator();

            for (int i = 0; i < 6; i++)
            {
                if (boolGen.Sample() == 1)
                {
                    var character = characterGen.GenerateCharacter();
                    var position  = findRandomPosition(room);
                    character.Transform.Position = position;
                    room.Entities.Add(character);
                }
            }
            for (int i = 0; i < 6; i++)
            {
                if (boolGen.Sample() == 1)
                {
                    var chest    = new Chest();
                    var position = findRandomPosition(room);
                    chest.Transform.Position = position;
                    var itemCount = randomItemCount();
                    chest.Items = new List <Item>();
                    for (int j = 0; j < itemCount; j++)
                    {
                        chest.Items.Add(itemGen.GenerateItem());
                    }
                    room.Entities.Add(chest);
                }
            }

            lastRoom = room;
            first    = false;

            return(room);
        }
        private OrderTypes CalculateTradeOrderType()
        {
            var tradeOrderTypeSample = DiscreteUniform.Sample(0, 1);

            var tradeOrderType = (OrderTypes)tradeOrderTypeSample;

            return(tradeOrderType);
        }
示例#17
0
        private Order[] SingularCancelledOrder(EquityInstrumentIntraDayTimeBar security, Market exchange)
        {
            var cancelledTradeOrderValue = DiscreteUniform.Sample(
                this._valueOfSingularCancelledTradeThreshold,
                10000000);
            var order = this.OrderForValue(OrderStatus.Cancelled, cancelledTradeOrderValue, security, exchange);

            return new[] { order };
        }
示例#18
0
        static void LoadMultiplication(out HashSet <TrainingData> data, int digits, int n)
        {
            data = new HashSet <TrainingData>();
            DiscreteUniform rand = new DiscreteUniform(1, (int)Math.Pow(10, digits) - 1);

            for (var i = 0; i < n; i++)
            {
                double       x     = rand.Sample();
                double       y     = rand.Sample();
                double       z     = x * y;
                TrainingData td    = new TrainingData(2, 1);
                double       scale = Math.Pow(10, digits);
                td.Data[0]  = x / scale;
                td.Data[1]  = y / scale;
                td.Response = DenseVector.Create(1, z / Math.Pow(10, 2 * digits));

                data.Add(td);
            }
        }
示例#19
0
        public static ITSLTopLevelElement GenerateCell(this TSLGeneratorContext context)
        {
            var name           = $"CellStruct_{context.TopLevelElementCount + 1}";
            var numberOfFields = DiscreteUniform.Sample(context.MasterRandom, StructSettings.MinFieldNumber, StructSettings.MaxFieldNumber);
            var fields         = context.RandomFields().Take(numberOfFields).ToArray();
            var result         = new TSLCell(name, fields);

            context.Cells.Add(result);
            return(result);
        }
示例#20
0
        /// <summary>
        /// Determine the number of arrivals in time window (15 minutes) and their arrival times
        /// </summary>
        /// <param name="mean">Average number of arrivals</param>
        /// <returns></returns>
        public static int[] arrivingPassengers(double mean)
        {
            var arrivals = Poisson.Sample(mean);
            var times    = new int[arrivals];

            for (int i = 0; i < arrivals; i++)
            {
                times[i] = DiscreteUniform.Sample(0, 899);
            }
            return(times);
        }
示例#21
0
        private void MutateNetworkTopology(Chromosome chromosome)
        {
            var inputCountDistribution        = new DiscreteUniform(1 + _parameters.MinSensorCount, 1 + _parameters.MaxSensorCount);
            var hiddenNeuronCountDistribution = new DiscreteUniform(_parameters.MinHiddenLayerNeuronCount, _parameters.MaxHiddenLayerNeuronCount);

            if (!ShouldMutate())
            {
                return;
            }

            int oldInputCount = chromosome.InputCount;

            chromosome.InputCount = inputCountDistribution.Sample();
            if (oldInputCount != chromosome.InputCount)
            {
                for (int i = 0; i < chromosome.HiddenLayerNeurons.Count; i++)
                {
                    var newNeuronData = new float[chromosome.InputCount + 1];
                    CopyAndFill(chromosome.HiddenLayerNeurons[i], newNeuronData);
                    chromosome.HiddenLayerNeurons[i] = newNeuronData;
                }
            }

            int oldHiddenLayerNeuronCount = chromosome.HiddenLayerNeuronCount;

            chromosome.HiddenLayerNeuronCount = hiddenNeuronCountDistribution.Sample();

            if (oldHiddenLayerNeuronCount != chromosome.HiddenLayerNeuronCount)
            {
                int diff = oldHiddenLayerNeuronCount - chromosome.HiddenLayerNeuronCount;
                if (diff > 0)
                {
                    for (int i = 0; i < diff; i++)
                    {
                        int index = new DiscreteUniform(0, chromosome.HiddenLayerNeurons.Count - 1).Sample();
                        chromosome.HiddenLayerNeurons.RemoveAt(index);
                    }
                }
                else
                {
                    for (int i = 0; i < Math.Abs(diff); i++)
                    {
                        chromosome.HiddenLayerNeurons.Add(NewNeuron(chromosome.InputCount));
                    }
                }

                for (int i = 0; i < chromosome.OutputLayerNeurons.Count; i++)
                {
                    var newNeuronData = new float[chromosome.HiddenLayerNeuronCount + 1];
                    CopyAndFill(chromosome.OutputLayerNeurons[i], newNeuronData);
                    chromosome.OutputLayerNeurons[i] = newNeuronData;
                }
            }
        }
示例#22
0
        private void setPrice(Equipment equipment)
        {
            int price = Convert.ToInt32(Normal.Sample(StoreConfig.MEAN_GOLD / 5.0d, StoreConfig.STDDEV_GOLD / 5.0d));

            foreach (KeyValuePair <int, (Attribute, int)> bonus in equipment.bonuses)
            {
                price += bonus.Value.Item2 * DiscreteUniform.Sample(5, 15);
            }

            equipment.price = price;
        }
示例#23
0
        public static ITSLTopLevelElement GenerateStruct(this TSLGeneratorContext context)
        {
            var name           = $"Struct_{context.TopLevelElementCount + 1}";
            var numberOfFields = DiscreteUniform.Sample(context.MasterRandom, StructSettings.MinFieldNumber, StructSettings.MaxFieldNumber);
            var fields         = context.RandomFields().Take(numberOfFields);
            // TODO(leasunhy): generate attributes
            var result = new TSLStruct(name, fields);

            context.AddStruct(result);
            return(result);
        }
示例#24
0
        private static string RandomString(Random random)
        {
            // TODO(leasunhy): extend alphabet or generate random chars
            var builder = new StringBuilder();
            var length  = DiscreteUniform.Sample(random, 0, RandomValueSettings.MaxStringLength);

            for (int i = 0; i < length; ++i)
            {
                builder.Append(RandomValueSettings.StringAlphabet.Choice(random));
            }
            return(builder.ToString());
        }
        private IReadOnlyCollection <int> SecuritiesToTrade(EquityIntraDayTimeBarCollection frame, int securitiesToTrade)
        {
            var upperLimit           = frame.Securities.Count - 1;
            var securitiesToTradeIds = new List <int>();

            for (var count = 0; count < securitiesToTrade; count++)
            {
                securitiesToTradeIds.Add(DiscreteUniform.Sample(0, upperLimit));
            }

            return(securitiesToTradeIds);
        }
示例#26
0
        private void HasPlanets()
        {
            int intNum = DiscreteUniform.Sample(1, 3);

            if ((intNum == 2 || intNum == 1) && StarType != GlobalConstants.StarType.O && StarType != GlobalConstants.StarType.B)
            {
                HasPanets = true;
            }
            else
            {
                HasPanets = false;
            }
        }
示例#27
0
 public static int DiscreteUniform(int lower, int upper, string sourceLocation)
 {
     try
     {
         DiscreteUniform discreteUniform = new DiscreteUniform(lower, upper, _randomSource);
         return(discreteUniform.Sample());
     }
     catch (Exception e)
     {
         Console.WriteLine($"\n{e.Message} {sourceLocation}");
         Environment.Exit(1);
         return(0);
     }
 }
示例#28
0
        private long CalculateADailyVolume(SecurityPriceSnapshotDto dto)
        {
            if (dto.DailyVolume > 0)
            {
                return(dto.DailyVolume);
            }

            if (dto.MarketCapUsd == 0 || dto.OpenPrice == 0)
            {
                return(DiscreteUniform.Sample(1000000, 10000000));
            }

            return((long)(dto.MarketCapUsd / dto.OpenPrice));
        }
示例#29
0
        private void SetPlanetTypeAndColor()
        {
            GlobalConstants.PlanetoidType PType = (GlobalConstants.PlanetoidType)Normal.Sample(4, 2.16);

            switch (PType)
            {
            case GlobalConstants.PlanetoidType.GAS_GIANT:
                Body.FillColor = new Color(226, 130, 106);
                Body.Radius    = DiscreteUniform.Sample(12, 25);
                break;

            case GlobalConstants.PlanetoidType.FROZEN:
                Body.FillColor = Color.Cyan;
                Body.Radius    = DiscreteUniform.Sample(4, 9);

                break;

            case GlobalConstants.PlanetoidType.ROCKY:
                Body.FillColor = new Color(86, 74, 71);
                Body.Radius    = DiscreteUniform.Sample(4, 9);

                break;

            case GlobalConstants.PlanetoidType.TERRAN:
                Body.FillColor = Color.Green;
                Body.Radius    = DiscreteUniform.Sample(4, 8);

                break;

            case GlobalConstants.PlanetoidType.WATER_WORLD:
                Body.FillColor = Color.Blue;
                Body.Radius    = DiscreteUniform.Sample(4, 8);
                break;

            case GlobalConstants.PlanetoidType.VOLCANIC:
                Body.FillColor = Color.Red + Color.Yellow;
                Body.Radius    = DiscreteUniform.Sample(4, 6);
                break;

            case GlobalConstants.PlanetoidType.TOXIC:
                Body.FillColor = Color.Green + Color.Yellow;
                Body.Radius    = DiscreteUniform.Sample(4, 8);
                break;

            default:
                Body.FillColor = new Color(226, 130, 106);
                Body.Radius    = DiscreteUniform.Sample(12, 25);
                break;
            }
        }
示例#30
0
        private Order OrderForValue(
            OrderStatus status,
            decimal value,
            EquityInstrumentIntraDayTimeBar security,
            Market exchange)
        {
            var volume = (int)(value / security.SpreadTimeBar.Ask.Value + 1);
            var orderPosition = (OrderDirections)DiscreteUniform.Sample(0, 3);

            var cancelledDate = status == OrderStatus.Cancelled ? (DateTime?)DateTime.UtcNow : null;
            var filledDate = status == OrderStatus.Filled ? (DateTime?)DateTime.UtcNow : null;

            var order = new Order(
                security.Security,
                exchange,
                null,
                Guid.NewGuid().ToString(),
                DateTime.UtcNow,
                "order-v1",
                "order-v1",
                "order-group-v1",
                DateTime.UtcNow,
                DateTime.UtcNow,
                null,
                null,
                cancelledDate,
                filledDate,
                OrderTypes.MARKET,
                orderPosition,
                security.SpreadTimeBar.Price.Currency,
                security.SpreadTimeBar.Price.Currency,
                OrderCleanDirty.NONE,
                null,
                security.SpreadTimeBar.Price,
                security.SpreadTimeBar.Price,
                volume,
                volume,
                "trader-1",
                "trader one",
                "clearing-agent",
                "dealing-instructions",
                new OrderBroker(string.Empty, string.Empty, "Mr Broker", DateTime.Now, true),
                null,
                null,
                OptionEuropeanAmerican.NONE,
                new DealerOrder[0]);

            return order;
        }
 public void CanSample()
 {
     var n = new DiscreteUniform(0, 10);
     n.Sample();
 }