/// <summary>
 /// Constructor
 /// </summary>
 /// <param name="lane"></param>
 public StayInLaneState(ArbiterLane lane, Probability confidence, IState previous)
 {
     this.Lane = lane;
     this.internalLaneState = new InternalState(lane.LaneId, lane.LaneId, confidence);
     this.IgnorableWaypoints = new List<IgnorableWaypoint>();
     this.CheckPreviousState(previous);
 }
Exemplo n.º 2
0
        /// <summary>
        /// </summary>
        private static float getPrediction(IEnumerable<string> pTokens, TokenCollection pFirst, TokenCollection pSecond)
        {
            Probability prob = new Probability();

            foreach (string token in pTokens)
            {
                int firstCount = pFirst.get(token);
                int secondCount = pSecond.get(token);

                if (firstCount == 0 && secondCount == 0)
                {
                    continue;
                }

                float probability = CalcProbability(prob, firstCount, pFirst.Sum, secondCount, pSecond.Sum);

                Console.WriteLine(@"{0}: [{1}] ({2}-{3}), ({4}-{5})",
                    token,
                    probability,
                    firstCount,
                    pFirst.Sum,
                    secondCount,
                    pSecond.Sum);
            }

            return prob.Combine();
        }
Exemplo n.º 3
0
            public void ReturnTrueIfTheInstancesAreTheSameObject()
            {
                var probability = new Probability(0.25m);
                var otherProbability = probability;

                Assert.That(otherProbability, Is.EqualTo(probability));
            }
Exemplo n.º 4
0
            public void ReturnFalseIfTheInstancesRepresentDifferentValues()
            {
                var probability = new Probability(0.25m);
                var otherProbability = new Probability(1/3);

                Assert.That(otherProbability, Is.Not.EqualTo(probability));
            }
Exemplo n.º 5
0
            public void ReturnTrueIfTheInstancesRepresentTheSameValue()
            {
                var probability = new Probability(0.25m);
                var otherProbability = new Probability(0.25m);

                Assert.That(otherProbability, Is.EqualTo(probability));
            }
Exemplo n.º 6
0
            public void ReturnThisProbabilityMultipliedByTheArgument(decimal firstProbability, decimal secondProbability)
            {
                var probability = new Probability(firstProbability);

                var combinedProbability = probability.CombinedWith(new Probability(secondProbability));

                Assert.That(combinedProbability, Is.EqualTo(new Probability(firstProbability * secondProbability)));
            }
Exemplo n.º 7
0
            public void ReturnAPlusBLessAMultipliedByB(decimal a, decimal b)
            {
                var probabilityOfA = new Probability(a);
                var probabilityOfB = new Probability(b);

                var eitherEvent = probabilityOfA.Either(probabilityOfB);

                Assert.That(eitherEvent, Is.EqualTo(new Probability(a + b - (a*b))));
            }
Exemplo n.º 8
0
 public void ShouldTestEquals()
 {
     var probabilityOne = new Probability(0.5);
     Assert.That(probabilityOne,Is.EqualTo(probabilityOne));
     Assert.True(probabilityOne.Equals(new Probability(0.5)));
     Assert.False(probabilityOne.Equals(new Probability(1.0)));
     Assert.False(probabilityOne.Equals(null));
     Assert.False(probabilityOne.Equals(new object()));
 }
Exemplo n.º 9
0
        public void Test_NaN()
        {
            Probability p = new Probability();
            p.Add("one", 1.0);
            p.Add("two", 2.0);
            p.Add("three", double.NaN);

            Assert.AreEqual(2, p.Prob.Count);
        }
Exemplo n.º 10
0
        public CorrelationScoreTable(ScoreMethod method, int intensityBins, double[] binEdges)
        {
            _method = method;
            _binEdges = binEdges;
            IntensityBins = null;
            _intensityBinCount = intensityBins;
            WorstScore = new Probability<int>(0);

            _intensityHistogram = new Histogram<FitScore>(new CompareFitScoreByIntensity());
        }
Exemplo n.º 11
0
        /// <summary>
        /// Calculates a probability value based on statistics from two categories
        /// </summary>
        private static float CalcProbability(Probability pProb, float pFirstCount, float pFirstTotal, float pSecondCount,
                                             float pSecondTotal)
        {
            const float s = 1f;
            const float x = .5f;

            float bw = pFirstCount / pFirstTotal;
            float gw = pSecondCount / pSecondTotal;
            float pw = ((bw) / ((bw) + (gw)));
            float n = pFirstCount + pSecondCount;
            float fw = ((s * x) + (n * pw)) / (s + n);

            pProb.Log(fw);

            return fw;
        }
Exemplo n.º 12
0
        public void Test_Serializing()
        {
            Probability p = new Probability();
            p.Add("one", 1.0);
            p.Add("two", 2.0);
            p.Add("three", 3.0);
            Assert.AreEqual(3, p.Prob.Count);

            string str = p.ToString();
            p = new Probability(str);
            Assert.AreEqual(3, p.Prob.Count);
            Assert.IsTrue(p.Prob.ContainsKey("one"));
            Assert.IsTrue(p.Prob.ContainsKey("two"));
            Assert.IsTrue(p.Prob.ContainsKey("three"));
            Assert.IsTrue(p.Prob.ContainsValue(1.0));
            Assert.IsTrue(p.Prob.ContainsValue(2.0));
            Assert.IsTrue(p.Prob.ContainsValue(3.0));
        }
Exemplo n.º 13
0
 private void SpawnEnemy()
 {
     Instantiate(Probability.RandomInArray <GameObject>(enemyPrefabs), this.transform.position, Quaternion.identity, enemyHolder);
     numSpawns++;
     StartCoroutine(SpawnCooldown());
 }
Exemplo n.º 14
0
 /// <summary>
 /// Initialization with values as parameters
 /// </summary>
 /// <param name="a">Input A</param>
 /// <param name="b">Input B</param>
 public EitherFunction(Probability a, Probability b)
 {
     A = a;
     B = b;
 }
Exemplo n.º 15
0
        private static Dist <int> NextBirthday(int distinctBirthdays)
        {
            var probabilityOfSharedBirthday = Probability.FromDecimal(Math.Min(distinctBirthdays, 365) / 365M);

            return(Distribution.OneOf <int>(distinctBirthdays, distinctBirthdays + 1, probabilityOfSharedBirthday));
        }
Exemplo n.º 16
0
 protected void Awake()
 {
     _probability   = new Probability();
     _navMeshMapper = new NavMeshMapper();
 }
Exemplo n.º 17
0
 /// <summary>
 /// Initialization with values as parameters
 /// </summary>
 /// <param name="a">Input A</param>
 /// <param name="b">Input B</param>
 public EitherFunction(decimal a, decimal b)
 {
     A = new Probability(a);
     B = new Probability(b);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="initial"></param>
 /// <param name="target"></param>
 public InternalState(ArbiterLaneId initial, ArbiterLaneId target)
 {
     this.Initial = initial;
     this.Target = target;
     this.Confidence = new Probability(0.8, 0.2);
 }
Exemplo n.º 19
0
 /// <summary>
 /// Creates a two dimensional array of all rank probabilities.
 /// </summary>
 /// <returns>Two dimensional array where the first dimension are ranks 
 /// and the second dimension are ion types.</returns>
 public Probability<IonType>[,] GetProbabilities()
 {
     var ionTypes = IonTypes;
     var ranks = new Probability<IonType>[ionTypes.Length, MaxRanks];
     for (int i = 0; i < ionTypes.Length; i++)
     {
         for (int j = 0; j < MaxRanks+1; j++)
         {
             var ionType = ionTypes[i];
             ranks[i, j] = new Probability<IonType>(ionTypes[i], _rankTable[ionType][j], _rankTotals[j]);
         }
     }
     return ranks;
 }
Exemplo n.º 20
0
        public override void OnUpdate(int gameTime)
        {
            base.OnUpdate(gameTime);

            var position = Player.Position;

            if (!ScriptThread.GetVar <bool>("scr_hardcore").Value)
            {
                if (Function.Call <bool>(Hash.IS_OBJECT_NEAR_POINT, 0x9A3207B7, position.X, position.Y, position.Z, (float)random.Next(50, 200)) &&
                    position.DistanceTo(GameplayCamera.Position) < 700.0f &&
                    !flareMgr.CooldownActive &&
                    Probability.GetBoolean(0.0020f + intelligenceBias))
                {
                    flareMgr.Start();
                }

                /*(  if (Player.Vehicle.Ref.Health < Player.Vehicle.Ref.MaxHealth &&
                 *    !extinguisher.CooldownActive &&
                 *    Probability.GetBoolean(intelligenceBias) )
                 * {
                 *    ScriptMain.DebugPrint("use extinguisher (" + Name + ")");
                 *    extinguisher.Start();
                 * }*/
            }

            if (gameTime > state.NextDecisionTime)
            {
                // If we arent chasing a target, they have moved too far away, or have been chasing a target for a set amount of time, make a new decision.
                if (Player.ActiveTarget == null || Player.ActiveTarget.Ped.Ref.IsDead ||
                    position.DistanceTo(Player.ActiveTarget.Position) > 1000.0f ||
                    !Utility.IsPositionInArea(Player.ActiveTarget.Position, levelMgr.Level.Bounds.Min, levelMgr.Level.Bounds.Max) ||
                    Game.GameTime - attackStartedTime > 30000)
                {
                    MakeDecision();
                }

                state.SetNextDecisionTime(gameTime + random.Next(1000, 5000));
            }

            switch (state.Status)
            {
            case AIStatus.FightOther:
            {
                if (Player.ActiveTarget != null)
                {
                    if (Player.ActiveTarget.Position.DistanceTo(Player.Position) > 600.0f)
                    {
                        if (!tooFar)
                        {
                            var destination = Player.ActiveTarget.Position;

                            Function.Call(Hash.TASK_PLANE_MISSION,
                                          Player.Ped.Ref,
                                          Player.Vehicle.Ref,
                                          0,
                                          0,
                                          destination.X, destination.Y, destination.Z,
                                          6, 309.0, 26.0f, 200.0, 1000.0, 20.0);

                            tooFar = true;
                        }
                    }

                    else if (Function.Call <int>(Hash.GET_ACTIVE_VEHICLE_MISSION_TYPE, Player.Vehicle.Ref) != 6)
                    {
                        tooFar = false;
                        Player.PersueTarget(Player.ActiveTarget);
                        UI.ShowSubtitle("persuing " + Function.Call <int>(Hash.GET_ACTIVE_VEHICLE_MISSION_TYPE, Player.Vehicle.Ref).ToString());
                    }
                }


                break;
            }

            case AIStatus.RandomFlight:
            {
                if (position.DistanceTo(destination) < 15.0f)
                {
                    SetRandomDestination();

                    ScriptMain.DebugPrint("Set new random destination for " + Player.Name);
                }

                else if (Player.Position.DistanceTo(sessionMgr.Current.Players[0].PlayerRef.Position) < 1000.0f &&
                         Player.Info.Sess.TeamNum != sessionMgr.Current.Players[0].TeamIdx)
                {
                    Player.PersueTarget(sessionMgr.Current.Players[0].PlayerRef);

                    state.Status = AIStatus.FightOther;
                }

                break;
            }
            }

            for (int i = 0; i < sessionMgr.Current.NumPlayers; i++)
            {
                if (gameTime - lastShotAtTime > 900)
                {
                    var otherPlayer = sessionMgr.Current.Players[i];

                    if (otherPlayer.TeamIdx == Player.Info.Sess.TeamNum)
                    {
                        continue;
                    }

                    var p = otherPlayer.PlayerRef.Position;

                    var direction = Vector3.Normalize(p - position);

                    var otherHeading = otherPlayer.PlayerRef.Vehicle.Ref.Heading;

                    if (Probability.GetBoolean(0.1f + intelligenceBias) && position.DistanceTo(p) < 400.0f)
                    {
                        Function.Call(Hash.SET_VEHICLE_SHOOT_AT_TARGET, Player.Ped.Ref, otherPlayer.PlayerRef.Vehicle.Ref, p.X, p.Y, p.Z);

                        ScriptMain.DebugPrint("Shoot at target (" + Player.Name + " > " + otherPlayer.PlayerRef.Name + ") team idx:" + otherPlayer.PlayerRef.Info.Sess.TeamNum.ToString() + " sess team:" + otherPlayer.TeamIdx);

                        lastShotAtTime = gameTime;
                    }
                }
            }
        }
Exemplo n.º 21
0
 public int Compare(Probability <IonType> x, Probability <IonType> y)
 {
     return(String.Compare(x.Label.Name, y.Label.Name, StringComparison.Ordinal));
 }
Exemplo n.º 22
0
 protected bool Equals(Probability other)
 {
     return rawProbability.Equals(other.rawProbability);
 }
Exemplo n.º 23
0
        public override int HandleProbabilisticChoice(Probability p0, Probability p1, Probability p2)
        {
            var choice = HandleProbabilisticChoice(3);

            switch (choice)
            {
            case 0:
                SetProbabilityOfLastChoice(p0);
                return(choice);

            case 1:
                SetProbabilityOfLastChoice(p1);
                return(choice);

            default:
                SetProbabilityOfLastChoice(p2);
                return(choice);
            }
        }
Exemplo n.º 24
0
 public Probability Either(Probability other)
 {
     return new Probability(rawProbability + other.rawProbability - (rawProbability * other.rawProbability));
 }
Exemplo n.º 25
0
        private void UpdatePulledEntities(int gameTime, float maxDistanceDelta)
        {
            float verticalForce = ScriptThread.GetVar <float>("vortexVerticalPullForce");

            float horizontalForce = ScriptThread.GetVar <float>("vortexHorizontalPullForce");

            float topSpeed = ScriptThread.GetVar <float>("vortexTopEntitySpeed");

            for (var e = 0; e < _activeEntityCount; e++)
            {
                var entity = _activeEntities[e].Entity;

                var dist = Vector2.Distance(entity.Position.Vec2(), _position.Vec2());

                if (dist > maxDistanceDelta - 12.6f || entity.HeightAboveGround > 300.0f)
                {
                    RemoveEntity(e);
                    continue;
                }

                var targetPos = new Vector3(_position.X + _activeEntities[e].XBias,
                                            _position.Y + _activeEntities[e].YBias, entity.Position.Z);

                var direction = Vector3.Normalize(targetPos - entity.Position);

                var forceBias = Probability.NextFloat();

                var force = ForceScale * (forceBias + forceBias / dist);

                if (_activeEntities[e].IsPlayer)
                {
                    if (gameTime - _lastPlayerShapeTestTime > 1000)
                    {
                        var raycast = World.Raycast(entity.Position, targetPos, IntersectOptions.Map);

                        _lastRaycastResultFailed = raycast.DitHitAnything;

                        _lastPlayerShapeTestTime = gameTime;
                    }

                    if (_lastRaycastResultFailed)
                    {
                        continue;
                    }

                    verticalForce   *= 1.45f;
                    horizontalForce *= 1.5f;
                }

                if (entity.Model.IsPlane)
                {
                    force         *= 6.0f;
                    verticalForce *= 6.0f;
                }

                // apply a directional force pulling them into the tornado...
                entity.ApplyForce(direction * horizontalForce,
                                  new Vector3(Probability.NextFloat(), 0,
                                              Probability.GetScalar()));

                var upDir = Vector3.Normalize(new Vector3(_position.X, _position.Y, _position.Z + 1000.0f) -
                                              entity.Position);
                // apply vertical forces
                entity.ApplyForceToCenterOfMass(upDir * verticalForce);

                var cross = Vector3.Cross(direction, Vector3.WorldUp);

                // move them along side the vortex.
                entity.ApplyForceToCenterOfMass(Vector3.Normalize(cross) * force *
                                                horizontalForce);

                Function.Call(Hash.SET_ENTITY_MAX_SPEED, entity.Handle, topSpeed);
            }
        }
 /// <summary>
 /// Creates a new instance of <see cref="AssessmentSectionCategory"/>.
 /// </summary>
 /// <param name="categoryGroup">The input to calculate the derived macro stability inwards input.</param>
 /// <param name="lowerBoundary">The input to calculate the derived macro stability inwards input.</param>
 /// <param name="upperBoundary">The input to calculate the derived macro stability inwards input.</param>
 /// <exception cref="AssemblyToolKernelException">Thrown when <paramref name="lowerBoundary"/> is not a valid probability.</exception>
 /// <exception cref="AssemblyToolKernelException">Thrown when <paramref name="upperBoundary"/> is not a valid probability.</exception>
 /// <exception cref="AssemblyToolKernelException">Thrown when <paramref name="lowerBoundary"/> exceeds <paramref name="upperBoundary"/>.</exception>
 public AssessmentSectionCategory(AssessmentSectionCategoryGroup categoryGroup, Probability lowerBoundary, Probability upperBoundary)
     : base(categoryGroup, lowerBoundary, upperBoundary)
 {
 }
Exemplo n.º 27
0
            public void ReturnThisProbabilitySubtractedFrom1(decimal rawProbability)
            {
                var probability = new Probability(rawProbability);

                var inverseProbability = probability.InverseOf();

                Assert.That(inverseProbability, Is.EqualTo(new Probability(1 - rawProbability)));
            }
Exemplo n.º 28
0
 public static void AssertEqualProbabilities(Probability expected, Probability actual)
 {
     TestBase.AssertEqualProbabilities(expected.ToDecimal(), actual);
 }
Exemplo n.º 29
0
 public Probability Either(Probability probability)
 {
     return new Probability(_probability + probability._probability - CombinedWith(probability)._probability);
 }
Exemplo n.º 30
0
 public static void AssertEqualProbabilities(decimal expected, Probability actual)
 {
     Assert.AreEqual(expected, actual);
 }
        // calculates sensor model
        private Probability Et(int tp1, bool ut)
        {
            // standard probability of posterior agreeing with internal lane est
            Probability eStandard = new Probability(0.65, 0.35);

            // modify probabilities off of consistency
            Probability et = eStandard;

            // return
            return et;
        }
Exemplo n.º 32
0
 public static void AssertEqualProbabilities(Probability expected, Probability actual, double delta)
 {
     TestBase.AssertEqualProbabilities(expected.ToDouble(), actual, delta);
 }
Exemplo n.º 33
0
    /**
     * Returns all hexes that surround the given hex, in the map, at a given radius
     * Passing a non-positive value for the radius will simply yeild a singleton
     * containing the given hex.
     */
    private List<HexScript> findArea(HexScript center, int radius, Probability variation)
    {
        List<HexScript> to_fill = new List<HexScript>();
        to_fill.Add(center);

        // find remaining layers
        if (radius > 0) {
            List<HexScript> initial = new List<HexScript>();
            initial.Add(center);
            addNextLayer(initial, to_fill, radius, variation);
        }

        return to_fill;
    }
Exemplo n.º 34
0
 public static void AssertEqualProbabilities(double expected, Probability actual)
 {
     AssertEqualProbabilities(expected, actual, 0);
 }
Exemplo n.º 35
0
 /// <summary>
 /// Returns the cumulative distribution function.
 /// </summary>
 /// <param name="k"></param>
 /// <returns></returns>
 public double CumulativeDistributionFunction(int k)
 {
     return(Probability.Binomial(k, n, p));
 }
Exemplo n.º 36
0
 public static void AssertEqualProbabilities(double expected, Probability actual, double delta)
 {
     Assert.AreEqual(expected, actual.ToDouble(), delta);
 }
Exemplo n.º 37
0
 private void AddIonProbability(Probability<IonType> probability)
 {
     var name = probability.Label;
     if (_ionFrequencies.ContainsKey(name))
         _ionFrequencies[name] += probability;
     else
         _ionFrequencies.Add(name, probability);
 }
 public double Quantile(Probability p) => Mu + Sigma * (Pow(p, A) - Pow(1 - p, B));
Exemplo n.º 39
0
 private static int IndexOfProbabilityExceedingBound(IEnumerable <Probability> probabilities, Probability lowerBound)
 {
     return(probabilities
            .Select((p, k) => new KeyValuePair <int, Probability>(k, p))
            .Where(item => item.Value > lowerBound)
            .Min(item => item.Key));
 }
Exemplo n.º 40
0
 /// <summary>
 /// Returns the cumulative distribution function.
 /// </summary>
 public double cdf(double x)
 {
     return(Probability.Gamma(alpha, lambda, x));
 }
Exemplo n.º 41
0
        public void MinimumGroupSizeWhereProbabilityOf2SharedBirthdaysExceedsBound()
        {
            var probOfSharedBirthdays = ComputeProbabilitiesOfSharedBirthdays();

            Assert.AreEqual(15, IndexOfProbabilityExceedingBound(probOfSharedBirthdays, Probability.FromDecimal(.25M)));
            Assert.AreEqual(23, IndexOfProbabilityExceedingBound(probOfSharedBirthdays, Probability.FromDecimal(.5M)));
            Assert.AreEqual(32, IndexOfProbabilityExceedingBound(probOfSharedBirthdays, Probability.FromDecimal(.75M)));
            Assert.AreEqual(57, IndexOfProbabilityExceedingBound(probOfSharedBirthdays, Probability.FromDecimal(.99M)));
            Assert.AreEqual(70, IndexOfProbabilityExceedingBound(probOfSharedBirthdays, Probability.FromDecimal(.999M)));
        }
Exemplo n.º 42
0
    /**
     * Finds all hexes that are adjacent to any hex in prev_layer at a given radius from the hexes in prev_layer, that
     * do not exist in total, with no duplicates. Ideally, prev_layer is a subset of total. Passing a non-positive
     * radius will yield no change. Variation should be a float between 0.0 and 1.0 inclusive coupled with a static decay
     * value that will reduce the probability on susequent layer calls. Contrary to logic, the greater the variability
     * the greater the chance of a uniform shape being formed from the hexes in total.
     */
    private void addNextLayer(List<HexScript> prev_layer, List<HexScript> total, int radius, Probability variation)
    {
        // based case
        if (radius <= 0) { return; }

        List<HexScript> cur_layer = new List<HexScript>();
        // Find hexes, which have not already been found, adjacent to any hex in the previous layer
        foreach (HexScript hex in prev_layer) {
            // find all adjacent hexes
            for (int pos = 0; pos < 6; ++pos) {
                HexScript adj_hex = adjacentHexTo(hex, pos);

                if ( (variation == null || UnityEngine.Random.value <= variation.getProbability()) && adj_hex != null && !total.Contains(adj_hex)) {
                    cur_layer.Add(adj_hex);
                    total.Add(adj_hex); // add to total as well
                }
            }
        }
        // avoid cutting off the generation of the area because of an empty layer
        if (cur_layer.Count == 0) { cur_layer = prev_layer; }

        if (variation != null) { variation.reduce(); }
        // find the next layer
        addNextLayer(cur_layer, total, radius - 1, variation);
    }
Exemplo n.º 43
0
        public void can_calculate_probability_of_inverse_event()
        {
            var probability = new Probability();

            Assert.Equal(0.4, probability.CalculateProbabilityOfInverse(0.6));
        }
 public double Quantile(Probability p) => - Log(1 - p) / Rate;
Exemplo n.º 45
0
 public Probability CombinedWith(Probability probability)
 {
     return new Probability(_probability * probability._probability);
 }
 /// <summary>
 /// Creates a new instance of <see cref="FailureMechanismCategory"/>.
 /// </summary>
 /// <param name="categoryGroup">The input to calculate the derived macro stability inwards input.</param>
 /// <param name="lowerBoundary">The input to calculate the derived macro stability inwards input.</param>
 /// <param name="upperBoundary">The input to calculate the derived macro stability inwards input.</param>
 /// <exception cref="AssemblyToolKernelException">Thrown when <paramref name="lowerBoundary"/> is not a valid probability.</exception>
 /// <exception cref="AssemblyToolKernelException">Thrown when <paramref name="upperBoundary"/> is not a valid probability.</exception>
 /// <exception cref="AssemblyToolKernelException">Thrown when <paramref name="lowerBoundary"/> exceeds <paramref name="upperBoundary"/>.</exception>
 public FailureMechanismCategory(FailureMechanismCategoryGroup categoryGroup, Probability lowerBoundary, Probability upperBoundary)
     : base(categoryGroup, lowerBoundary, upperBoundary)
 {
 }
Exemplo n.º 47
0
 protected bool Equals(Probability other)
 {
     return _probability == other._probability;
 }
Exemplo n.º 48
0
 public override string ToString()
 {
     return($"{HomeTeam} - {AwayTeam} - {Probability.ToString("0.00")}% - {EnumUtility.GetDescriptionFromEnumValue(Result)}");
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="initial"></param>
 /// <param name="target"></param>
 public InternalState(ArbiterLaneId initial, ArbiterLaneId target, Probability confidence)
 {
     this.Initial = initial;
     this.Target = target;
     this.Confidence = confidence;
 }
Exemplo n.º 50
0
 public TestCategoryBase(double category, Probability lowerLimit, Probability upperLimit) : base(category, lowerLimit, upperLimit)
 {
 }
        // f1:t+1 = sFORWARD(f1:t, et+1)
        private Probability Forward()
        {
            // get t and t+1
            int tp1 = this.FilteredEstimate.Count;
            int t = tp1 - 1;

            // check numbering
            if (t < 0)
                return new Probability(0.9, 0.2);

            // transition
            Probability transition  = new Probability(0.7, 0.3);

            // calculate prediction from t-1 to t
            // sum(xt): P(Xt+1|xt)P(xt|e1:t)
            Probability prediction = transition * FilteredEstimate[t];
            prediction = new Probability(Math.Max(prediction.T, 0.00001), Math.Max(prediction.F, 0.00001), true);

            // calculate boolean evidence for t+1
            bool ut = this.Ut(PosteriorEvidence[tp1], tp1);
            //Probability ct = this.Ct(this.PosteriorEvidence, ut);

            // calculate sensor model given the estiamtes agree
            Probability evidence = ut ? new Probability(0.9, 0.2) : new Probability(0.2, 0.9);

            //update with evidence for time t, calculate P(et+1|Xt+1) * (PreviousStep)
            //Probability filtered = ut ? et * prediction : et.Invert() * prediction;
            Probability filtered = evidence * prediction;

            // normalize
            Probability nFiltered = filtered.Normalize();

            // return
            return nFiltered;
        }
Exemplo n.º 52
0
 public double Quantile(Probability p) => Mean + StandardDeviation * Constants.Sqrt2 * ErrorFunction.InverseValue(2 * p - 1);
Exemplo n.º 53
0
        public void can_calculate_probability_of_either_events()
        {
            var probability = new Probability();

            Assert.Equal(0.8, probability.CalculateProbabilityOfEither(0.6, 0.5));
        }
Exemplo n.º 54
0
 public double Quantile(Probability p) => inverseCdf.GetValue(p);
Exemplo n.º 55
0
 public double Quantile(Probability p) => Min + p * (Max - Min);
Exemplo n.º 56
0
    static public void Learn()
    {
        int threadCount;
        int threadCount2;

        ThreadPool.GetMaxThreads(out threadCount, out threadCount2);
        Console.WriteLine("スレッド数は" + threadCount + "です。");

        Console.WriteLine("世代数を入力してください。");
        int generationDestination = int.Parse(Console.ReadLine());

        Console.WriteLine("学習を開始します。");


        int nowGenerationIndex = 0;
        int index = 0;

        TetrisEnvironment.MinoKind[]      nexts        = new TetrisEnvironment.MinoKind[5];
        List <TetrisEnvironment.MinoKind> _leftMinoBag = new List <TetrisEnvironment.MinoKind>();

        Chromosome[] nowChromosome = new Chromosome[generationDestination];
        const int    FrameMax      = 10800;

        int[,] field = new int[10, 25];

        Random random = new Random();

        while (true)
        {
            for (int i = 0; i < generationDestination; i++)
            {
                float[] values = new float[11];
                values[0]  = random.Next(-100, 155);
                values[1]  = random.Next(-100, 155);
                values[2]  = random.Next(-100, 155);
                values[3]  = random.Next(-100, 155);
                values[4]  = random.Next(-100, 155);
                values[5]  = random.Next(-100, 155);
                values[6]  = random.Next(-100, 155);
                values[7]  = random.Next(-100, 155);
                values[8]  = random.Next(-100, 155);
                values[9]  = random.Next(-100, 155);
                values[10] = random.Next(-100, 155);

                nowChromosome[i].chromosome = CreateChromosome(values);
            }


Label:
            var values2 = DecodeChromosome(nowChromosome[index].chromosome);

            NewEvaluation.h_sumofheight = values2[0];
            NewEvaluation.h_dekoboko    = values2[1];
            NewEvaluation.h_holeCount   = values2[2];
            NewEvaluation.h_holeup1     = values2[3];
            NewEvaluation.h_holeup2     = values2[4];
            NewEvaluation.h_holeup3     = values2[5];
            NewEvaluation.h_holeup4     = values2[6];
            NewEvaluation.h_line1       = values2[7];
            NewEvaluation.h_line2       = values2[8];
            NewEvaluation.h_line3       = values2[9];
            NewEvaluation.h_line4       = values2[10];

            for (int x = 0; x < 10; x++)
            {
                for (int y = 0; y < 25; y++)
                {
                    field[x, y] = 0;
                }
            }
            Console.Clear();
            Console.WriteLine($"{nowGenerationIndex}世代 {index}/{generationDestination}\r\n\r\n");

            Console.WriteLine($"現在の評価\r\n" +
                              $"高さ合計:{ NewEvaluation.h_sumofheight}\r\n" +
                              $"1ライン消し:{ NewEvaluation.h_line1}\r\n" +
                              $"2ライン消し:{ NewEvaluation.h_line2}\r\n" +
                              $"3ライン消し:{ NewEvaluation.h_line3}\r\n" +
                              $"4ライン消し:{ NewEvaluation.h_line4}\r\n" +
                              $"でこぼこ:{ NewEvaluation.h_dekoboko}\r\n" +
                              $"穴:{ NewEvaluation.h_holeCount}\r\n" +
                              $"穴の上ミノ1:{ NewEvaluation.h_holeup1}\r\n" +
                              $"穴の上ミノ2:{ NewEvaluation.h_holeup2}\r\n" +
                              $"穴の上ミノ3:{ NewEvaluation.h_holeup3}\r\n" +
                              $"穴の上ミノ4:{ NewEvaluation.h_holeup4}\r\n");

            TetrisEnvironment.UpdateNexts(nexts, _leftMinoBag);
            TetrisEnvironment.UpdateNexts(nexts, _leftMinoBag);
            TetrisEnvironment.UpdateNexts(nexts, _leftMinoBag);
            TetrisEnvironment.UpdateNexts(nexts, _leftMinoBag);
            TetrisEnvironment.UpdateNexts(nexts, _leftMinoBag);
            var minotemp = TetrisEnvironment.UpdateNexts(nexts, _leftMinoBag);
            TetrisEnvironment.Mino nowMino = TetrisEnvironment.CreateMino(minotemp);
            bool canhold = true;
            TetrisEnvironment.MinoKind?hold = new TetrisEnvironment.MinoKind?();
            int  frameCount = 0;
            int  score      = 0;
            int  ren        = 0;
            bool backtoback = false;

            while (true)
            {
                var way = NewTetrisAI.Find(field, (int)nowMino.kind, Utility.Enum2IntArray(new TetrisEnvironment.MinoKind[1] {
                    nexts[0]
                }), 0, (int?)hold, canhold);

                way.way = way.way.Substring(0, way.way.IndexOf('5') + 1);
                foreach (char action in way.way)
                {
                    switch (int.Parse(action.ToString()))
                    {
                    case (int)TetrisEnvironment.Move.SoftDrop:
                        if (TetrisEnvironment.CheckValidPosition(field, nowMino.positions, new TetrisEnvironment.Vector2(0, -1)))
                        {
                            nowMino.positions[0] += new TetrisEnvironment.Vector2(0, -1);
                            nowMino.positions[1] += new TetrisEnvironment.Vector2(0, -1);
                            nowMino.positions[2] += new TetrisEnvironment.Vector2(0, -1);
                            nowMino.positions[3] += new TetrisEnvironment.Vector2(0, -1);

                            frameCount += MoveFrame;
                        }
                        break;

                    case (int)TetrisEnvironment.Move.HardDrop:
                        frameCount += MinoSet;
                        canhold     = true;
                        int count = 0;
                        while (true)
                        {
                            if (TetrisEnvironment.CheckValidPosition(field, nowMino.positions, new TetrisEnvironment.Vector2(0, count)))
                            {
                                count--;
                            }
                            else
                            {
                                count++; break;
                            }
                        }

                        nowMino.positions[0] += new TetrisEnvironment.Vector2(0, count);
                        nowMino.positions[1] += new TetrisEnvironment.Vector2(0, count);
                        nowMino.positions[2] += new TetrisEnvironment.Vector2(0, count);
                        nowMino.positions[3] += new TetrisEnvironment.Vector2(0, count);

                        foreach (var position in nowMino.positions)
                        {
                            field[position.x, position.y] = 1;
                        }

                        //ミノ消去ANDスコア加算
                        int clearedCount = TetrisEnvironment.CheckLine(field);

                        if (clearedCount == 4)
                        {
                            backtoback = true;
                        }
                        else
                        {
                            backtoback = false;
                        }

                        if (clearedCount == 0)
                        {
                            ren = 0;
                        }
                        else
                        {
                            ren++;
                        }
                        TetrisEnvironment.UpdateScore(clearedCount, ren, ref score, backtoback);

                        var temp2 = TetrisEnvironment.UpdateNexts(nexts, _leftMinoBag);
                        nowMino = TetrisEnvironment.CreateMino(temp2);

                        if (!TetrisEnvironment.CheckValidPosition(field, nowMino.positions, TetrisEnvironment.Vector2.Zero) || frameCount >= FrameMax)
                        {
                            //死亡


                            if (index == generationDestination - 1)
                            {    //次の世代に移行
                                List <Chromosome> newChromosomes = new List <Chromosome>();
                                List <Chromosome> tempList       = new List <Chromosome>();

                                nowChromosome[index].eval = score;


                                tempList.AddRange(nowChromosome);

                                tempList.Sort((a, b) => b.eval.CompareTo(a.eval));
                                score = 0;

                                //エリート方式で追加
                                for (int i = 0; i < generationDestination - 3; i++)
                                {
                                    newChromosomes.Add(new Chromosome(0, tempList[i].chromosome));
                                }

                                newChromosomes.Add(new Chromosome(0, GeneticAlgorithm.TwoPointCrossOver(tempList[0].chromosome, tempList[1].chromosome)));
                                newChromosomes.Add(new Chromosome(0, GeneticAlgorithm.TwoPointCrossOver(tempList[0].chromosome, tempList[2].chromosome)));
                                if (Probability.Percent(3))
                                {
                                    newChromosomes.Add(new Chromosome(0, GeneticAlgorithm.Mutation(tempList[0].chromosome)));
                                }
                                else
                                {
                                    newChromosomes.Add(new Chromosome(0, tempList[0].chromosome));
                                }


                                nowChromosome = newChromosomes.ToArray();
                                nowGenerationIndex++;
                                index = 0;
                            }
                            else
                            {
                                nowChromosome[index].eval = score;
                            }


                            index++;
                            goto Label;
                        }
                        break;

                    case (int)TetrisEnvironment.Move.Hold:
                        if (canhold)
                        {
                            canhold = false;
                            if (hold == null)
                            {
                                hold = nowMino.kind;

                                var temp = TetrisEnvironment.UpdateNexts(nexts, _leftMinoBag);
                                nowMino = TetrisEnvironment.CreateMino(temp);
                            }
                            else
                            {
                                var temp = nowMino.kind;
                                nowMino = TetrisEnvironment.CreateMino((TetrisEnvironment.MinoKind)hold);
                                hold    = temp;
                            }
                        }
                        break;

                    case (int)TetrisEnvironment.Move.Left:
                        if (TetrisEnvironment.CheckValidPosition(field, nowMino.positions, TetrisEnvironment.Vector2.MinusX1))
                        {
                            nowMino.positions[0] += TetrisEnvironment.Vector2.MinusX1;
                            nowMino.positions[1] += TetrisEnvironment.Vector2.MinusX1;
                            nowMino.positions[2] += TetrisEnvironment.Vector2.MinusX1;
                            nowMino.positions[3] += TetrisEnvironment.Vector2.MinusX1;

                            frameCount += MoveFrame;
                        }
                        break;

                    case (int)TetrisEnvironment.Move.LeftRotate:
                        if (TetrisEnvironment.RotateMino(TetrisEnvironment.Move.LeftRotate, ref nowMino, field))
                        {
                            frameCount += MoveFrame;
                        }
                        break;

                    case (int)TetrisEnvironment.Move.Right:
                        if (TetrisEnvironment.CheckValidPosition(field, nowMino.positions, TetrisEnvironment.Vector2.X1))
                        {
                            nowMino.positions[0] += TetrisEnvironment.Vector2.X1;
                            nowMino.positions[1] += TetrisEnvironment.Vector2.X1;
                            nowMino.positions[2] += TetrisEnvironment.Vector2.X1;
                            nowMino.positions[3] += TetrisEnvironment.Vector2.X1;

                            frameCount += MoveFrame;
                        }
                        break;

                    case (int)TetrisEnvironment.Move.RightRotate:
                        if (TetrisEnvironment.RotateMino(TetrisEnvironment.Move.RightRotate, ref nowMino, field))
                        {
                            frameCount += MoveFrame;
                        }

                        break;
                    }

                    //TetrisEnvironment.Print(field, nowMino.positions, false);
                    //Console.WriteLine("現在のミノ");
                    //Console.Write(nowMino.kind + "\r\n");
                    //Console.WriteLine("ネクスト");
                    //Console.Write(nexts[0]);
                    //Console.Write(nexts[1]);
                    //Console.Write(nexts[2]);
                    //Console.Write(nexts[3]);
                    //Console.Write(nexts[4] + "\r\n");
                    //Console.WriteLine("ホールド");
                    //Console.WriteLine(hold + "\r\n");
                    //Thread.Sleep(10);
                    ////Console.ReadKey();
                }
            }
        }
    }