Exemplo n.º 1
0
        public override object Part1()
        {
            var bots = Parse();
            var best = bots.MaxBy(x => x.R);

            return(bots.Count(b => Dist(best, (b.X, b.Y, b.Z)) <= best.R));
        }
Exemplo n.º 2
0
 /// <summary>
 /// Draws n samples from a distribution.
 /// This will throw an exception if the distribution contains any conditionals.
 /// </summary>
 public static IEnumerable <A> SampleN <A>(this Dist <A> dist, int n)
 {
     for (int i = 0; i < n; ++i)
     {
         yield return(dist.Sample());
     }
 }
Exemplo n.º 3
0
 public Dist <Samples <A> > Bind <B>(Dist <B> dist, Func <B, Dist <A> > bind)
 {
     return(from ps in dist.Run(new Smc <B>(numParticles))
            let unzipped = ps.Unzip()
                           from ys in unzipped.Item1.Select(bind).Sequence()
                           select Samples(ys.Zip(unzipped.Item2, ItemProb)));
 }
Exemplo n.º 4
0
        public static string RandomSample(int samples, int sampleSize, Dist f)
        {
            List <List <double> > allSamples = new List <List <double> >();

            for (int s = 1; s < samples; ++s)
            {
                List <double> sample = new List <double>();

                for (int e = 0; e < sampleSize; ++e)
                {
                    sample.Add(f());
                }

                allSamples.Add(sample);
            }

            List <double> Avgs = new List <double>();
            List <double> Stds = new List <double>();

            foreach (List <double> sample in allSamples)
            {
                Avgs.Add(sample.Average());
                Stds.Add(MathUtils.StandardDeviation(sample, false));
            }

            double finalAvg   = Avgs.Average();
            double finalStd   = MathUtils.StandardDeviation(Avgs, false);
            double elementStd = Stds.Average();

            return(String.Format($"Avg {finalAvg} , Std {finalStd}, ElementStd {elementStd}"));
        }
        /// <summary>
        /// Generates data for the hidden markov model
        /// </summary>
        public static Dist <List <Tuple <A, B> > > Sample <A, B>(
            Func <A, Dist <B> > emissionDist,
            Dist <List <A> > startDist,
            Func <A, Dist <A> > transitionDist,
            int numSamples
            )
        {
            Dist <List <Tuple <A, B> > > samples =
                from list in startDist
                let initial = list.First()
                              from emit in emissionDist(initial)
                              select new List <Tuple <A, B> > {
                Tuple(initial, emit)
            };

            while (numSamples > 0)
            {
                samples = from prev in samples
                          from next in transitionDist(prev.Last().Item1)
                          from emit in emissionDist(next)
                          select prev.Append(Tuple(next, emit)).ToList();

                numSamples -= 1;
            }
            return(samples);
        }
Exemplo n.º 6
0
 public RunIndependent3(Dist <T1> first, Dist <T2> second, Dist <T3> third, Func <T1, T2, T3, Dist <A> > run)
 {
     this.first  = first;
     this.second = second;
     this.third  = third;
     this.run    = run;
 }
        public void Nu_WrongValues(double d)
        {
            var i = (int)d;

            Assert.False(StudentsTDistribution.IsValidParam(i));
            Assert.False(Dist.IsValidNu(i));
            Assert.Throws <ArgumentOutOfRangeException>(() => { Dist.Nu = i; });
        }
        public A RunIndependent <B, C>(Dist <B> distB, Dist <C> distC, Func <B, C, Dist <A> > run)
        {
            var taskB = Task.Run(() => distB.RunParallel(new ParallelSampler <B>()));
            var taskC = Task.Run(() => distC.RunParallel(new ParallelSampler <C>()));

            Task.WaitAll(taskB, taskC);
            return(run(taskB.Result, taskC.Result).RunParallel(new ParallelSampler <A>()));
        }
Exemplo n.º 9
0
 public void Next_ManyRand()
 {
     for (var i = 0; i < Iterations; ++i)
     {
         Results[i] = Dist.Next();
     }
     AssertDist(Dist);
 }
Exemplo n.º 10
0
        public void Alpha_WrongValues(double d)
        {
            var i = (int)d;

            Assert.False(ErlangDistribution.AreValidParams(i, 1));
            Assert.False(Dist.IsValidAlpha(i));
            Assert.Throws <ArgumentOutOfRangeException>(() => { Dist.Alpha = i; });
        }
Exemplo n.º 11
0
        public void Beta_WrongValues(double d)
        {
            var i = (int)d;

            Assert.False(BinomialDistribution.AreValidParams(0.5, i));
            Assert.False(Dist.IsValidBeta(i));
            Assert.Throws <ArgumentOutOfRangeException>(() => { Dist.Beta = i; });
        }
Exemplo n.º 12
0
        public bool UpdateRange(Object CurObj)
        {
            float Distance = CurObj.GetDistance(CurObj.LastRangeCheck);

            if (Distance > 100)
            {
                CurObj.LastRangeCheck.X = CurObj.X;
                CurObj.LastRangeCheck.Y = CurObj.Y;
            }
            else
            {
                return(false);
            }

            List <Object> Objects = GetRangedObject(CurObj, 1);

            foreach (Object DistObj in Objects) // Ici on check tous les objets visibles
            {
                if (CurObj == DistObj)
                {
                    continue;
                }

                if (DistObj.IsPlayer() && !DistObj.GetPlayer().Client.IsPlaying())
                {
                    continue;
                }

                if (!CurObj.HasInRange(DistObj))
                {
                    CurObj.AddInRange(DistObj);
                    DistObj.AddInRange(CurObj);

                    if (CurObj.IsPlayer())
                    {
                        DistObj.SendMeTo(CurObj.GetPlayer());
                    }

                    if (DistObj.IsPlayer())
                    {
                        CurObj.SendMeTo(DistObj.GetPlayer());
                    }
                }
                else
                {
                }
            }

            List <Object> ToDel = CurObj._ObjectRanged.FindAll(dist => dist != null && dist.GetDistance(CurObj) > MAX_VISIBILITY_RANGE);

            foreach (Object Dist in ToDel)
            {
                CurObj.RemoveInRange(Dist);
                Dist.RemoveInRange(CurObj);
            }

            return(true);
        }
Exemplo n.º 13
0
        //For Debugging
        //private static void DrawMap(Dist[,] map)
        //{
        //    var width = map.GetLength(0);
        //    var height = map.GetLength(1);
        //    for (var x = 0; x < width; x++)
        //    {
        //        for (var y = 0; y < height; y++)
        //        {
        //            Console.Write($"{map[x, y].Id}");
        //        }
        //        Console.WriteLine();
        //    }
        //}

        private static (char, int) FillMap(Dist[,] map, Dictionary <char, Point> points)
        {
            /*Naive initial impl. went points first, and then multiple iterations of the map
             */
            var width  = map.GetLength(0);
            var height = map.GetLength(1);

            foreach (var p in points.Values)
            {
                for (var x = 0; x < width; x++)
                {
                    for (var y = 0; y < height; y++)
                    {
                        var d     = GetManhattanDistance(p, x, y);
                        var isInf = IsInfinite(x, y, width, height);

                        if ((map[x, y] == null) || //unmapped
                            (map[x, y].Id != p.Id && map[x, y].D > d))    //someone else further away
                        {
                            map[x, y] = new Dist {
                                Id = p.Id, D = d, IsInfinite = isInf
                            };
                        }
                        else if (map[x, y].Id != p.Id && map[x, y].D == d)
                        {
                            map[x, y] = new Dist {
                                Id = '.', D = d, IsInfinite = isInf
                            };
                        }
                    }
                }
            }

            //Flatten It
            var tmp = new Dist[width * height];

            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    tmp[y * width + x] = map[x, y];
                }
            }

            //Group By Cell Id & coun't the ones that are not touching infinity
            var r = tmp.GroupBy(k => k.Id)
                    .Where(w => !w.Any(d => d.IsInfinite))
                    .Select(s => new
            {
                Id    = s.Key,
                Count = s.Count()
            })
                    .OrderByDescending(o => o.Count)
                    .First();

            return(r.Id, r.Count);
        }
Exemplo n.º 14
0
 public static Prob Pdf(Dist <Matrix <double> > dist, Matrix <double> y)
 {
     if (dist is Primitive <Matrix <double> > )
     {
         var primitive = dist as Primitive <Matrix <double> >;
         return(Pdf(primitive.dist, y));
     }
     throw new ArgumentException("Can only calculate PDF for primitive distributions");
 }
        /// <summary>
        /// The metropolis algorithm with prior as proposal dist.
        /// It's a really slow mixing chain if the prior is too different from the posterior.
        /// </summary>
        /// <returns>A distribution of Markov chains</returns>
        public static Dist <IEnumerable <A> > MHPrior <A>(Dist <A> dist, int n)
        {
            var initial = new List <ItemProb <A> > {
                dist.WeightedPrior().Sample()
            };
            var chain = Iterate(n, dist.WeightedPrior, initial);

            return(chain.Select(ipList => ipList.Select(ip => ip.Item)));
        }
Exemplo n.º 16
0
        public A RunIndependent3 <B, C, D>(Dist <B> distB, Dist <C> distC, Dist <D> distD, Func <B, C, D, Dist <A> > run)
        {
            var taskB = StartTask(() => distB.RunParallel(new ParallelSampler <B>()));
            var taskC = StartTask(() => distC.RunParallel(new ParallelSampler <C>()));
            var taskD = StartTask(() => distD.RunParallel(new ParallelSampler <D>()));

            Task.WaitAll(taskB, taskC, taskD);
            return(run(taskB.Result, taskC.Result, taskD.Result).RunParallel(new ParallelSampler <A>()));
        }
Exemplo n.º 17
0
 public static Prob Pmf(Dist <int> dist, int y)
 {
     if (dist is Primitive <int> )
     {
         var primitive = dist as Primitive <int>;
         return(Pmf(primitive.dist, y));
     }
     throw new ArgumentException("Can only calculate pmf for primitive distributions");
 }
Exemplo n.º 18
0
 public static Prob Pmf <T>(Dist <T> dist, T k)
 {
     if (dist is Primitive <T> )
     {
         var primitive = dist as Primitive <T>;
         return(Pmf(primitive.dist, k));
     }
     throw new ArgumentException("Can only calculate PDF for primitive distributions");
 }
Exemplo n.º 19
0
        private void InitHatas(ResponseObservation observation)
        {
            FindBaseLocations(observation);
            SetBasePosionsByMinerals();

            var hatas = observation.Observation.RawData.Units.Where(d => d.UnitType == UnitTypes.HATCHERY && d.Alliance == Alliance.Self).ToList();

            if (hatas.Count() != Bases.Where(b => b.Taken).Count())
            {
                foreach (var h in hatas)
                {
                    foreach (var b in Bases)
                    {
                        if (Dist.Distance(b.Position, h.Pos) < 5)
                        {
                            b.Taken    = true;
                            b.Position = h.Pos;
                            b.BaseId   = h.Tag;
                        }
                    }
                }
            }

            if (MainBase == 0 && hatas != null)
            {
                MainBase = hatas.FirstOrDefault().Tag;
            }

            //if (hatas.Count() > 1 || hatas.Count() == 0)
            //    return;

            var minDist = float.MaxValue;
            var bas     = Bases[0];

            foreach (var b in Bases)
            {
                var dist = Dist.Distance(b.Position, hatas[0].Pos);
                if (dist < minDist)
                {
                    minDist = dist;
                    bas     = b;
                }
            }

            bas.BaseId = hatas[0].Tag;

            foreach (var b in Bases)
            {
                if (b.BaseId == MainBase)
                {
                    continue;
                }

                b.DistanceToMain = Dist.Distance(hatas[0].Pos, b.Position);
            }
        }
Exemplo n.º 20
0
 public void AlphaBeta_WrongValues(double a, double b)
 {
     Assert.Throws <ArgumentOutOfRangeException>(() =>
     {
         Assert.False(ContinuousUniformDistribution.AreValidParams(a, b));
         Dist.Alpha = Dist.Beta = a;
         Assert.False(Dist.IsValidBeta(b));
         Dist.Beta = b;
     });
 }
        public void Weights_WrongValues(double d1, double d2, double d3)
        {
            var w = new List <double> {
                d1, d2, d3
            };

            Assert.False(CategoricalDistribution.IsValidParam(w));
            Assert.False(Dist.AreValidWeights(w));
            Assert.Throws <ArgumentOutOfRangeException>(() => { Dist.Weights = w; });
        }
Exemplo n.º 22
0
        public void Integers_Next_SameOutput()
        {
            var integers = Dist.DistributedIntegers().GetEnumerator();

            for (var i = 0; i < Iterations; ++i)
            {
                integers.MoveNext();
                Assert.AreEqual(integers.Current, OtherDist.Next());
            }
        }
Exemplo n.º 23
0
        public void Integers_SameOutput()
        {
            var integers = Dist.DistributedIntegers().GetEnumerator();

            integers.MoveNext();
            for (var i = 0; i < Iterations; ++i, integers.MoveNext())
            {
                OtherDist.Next().ShouldBe(integers.Current);
            }
        }
Exemplo n.º 24
0
        public void Doubles_SameOutput()
        {
            var doubles = Dist.DistributedDoubles().GetEnumerator();

            doubles.MoveNext();
            for (var i = 0; i < Iterations; ++i, doubles.MoveNext())
            {
                Assert.AreEqual(OtherDist.NextDouble(), doubles.Current);
            }
        }
Exemplo n.º 25
0
        public void Reset_AfterOneRand()
        {
            if (!Dist.CanReset)
            {
                Assert.Pass();
            }
            var d = Dist.Next();

            Assert.True(Dist.Reset());
            Assert.AreEqual(d, Dist.Next());
        }
Exemplo n.º 26
0
        async Task BuildIndexType()
        {
            await BuildPaging(Data.Where(x => x.Raw.Type == PostType.Article).ToList(),
                              Dist.CreateSubdirectory("articles"));

            await BuildPaging(Data.Where(x => x.Raw.Type == PostType.Slides).ToList(),
                              Dist.CreateSubdirectory("slides"));

            await BuildPaging(Data.Where(x => x.Raw.Type == PostType.Note).ToList(),
                              Dist.CreateSubdirectory("notes"));
        }
Exemplo n.º 27
0
        public void Integers_ManyRand()
        {
            var integers = Dist.DistributedIntegers().GetEnumerator();

            integers.MoveNext();
            for (var i = 0; i < Iterations; ++i, integers.MoveNext())
            {
                Results[i] = integers.Current;
            }
            AssertDist(Dist);
        }
Exemplo n.º 28
0
        public void Doubles_ManyRand()
        {
            var doubles = Dist.DistributedDoubles().GetEnumerator();

            doubles.MoveNext();
            for (var i = 0; i < Iterations; ++i, doubles.MoveNext())
            {
                Results[i] = doubles.Current;
            }
            AssertDist(Dist);
        }
Exemplo n.º 29
0
        public int CompareTo(Node other)
        {
            int res = Dist.CompareTo(other.Dist);

            //if res and other is equal then apply different CompareTo() value (OrderedSet deletes any State if

            if (res == 0)
            {
                return(uniqueIndex.CompareTo(other.uniqueIndex));
            }
            return(res);
        }
Exemplo n.º 30
0
        public Dist <Samples <A> > Conditional(Func <A, Prob> lik, Dist <A> dist)
        {
            var updated = new Conditional <Samples <A> >(
                samples => samples.SumProbs(),

                from ps in dist.Run(new Smc <A>(numParticles))
                select ps.Select(ip => ItemProb(ip.Item, lik(ip.Item).Mult(ip.Prob)))
                );

            return(updated.Select(Importance.Normalize)
                   .SelectMany(Importance.Resample));
        }
Exemplo n.º 31
0
Arquivo: XSub.cs Projeto: knocte/netmq
        public XSub(Ctx parent, int tid, int sid)
            : base(parent, tid, sid)
        {
            m_options.SocketType = ZmqSocketType.Xsub;
            m_hasMessage = false;
            m_more = false;

            m_options.Linger = 0;
            m_fq = new FQ();
            m_dist = new Dist();
            m_subscriptions = new Trie();
        }
Exemplo n.º 32
0
 public FormMain()
 {
     InitializeComponent();
     dist = new Dist();
 }
Exemplo n.º 33
0
Arquivo: XPub.cs Projeto: knocte/netmq
        public XPub(Ctx parent, int tid, int sid)
            : base(parent, tid, sid)
        {
            m_options.SocketType = ZmqSocketType.Xpub;
            m_verbose = false;
            m_more = false;

            m_subscriptions = new Mtrie();
            m_dist = new Dist();
            m_pending = new Deque<Blob>();
        }