示例#1
0
        private ProjectedAfrCorrection AverangeCorrection(IEnumerable<LogLine> lines, float targetAfr)
        {
            return new ProjectedAfrCorrection()
            {
                AfrDiffPercent = (float)lines.WeightedAverage(
                    l => (l.AfrWideband.Value / targetAfr) * 100 - 100,
                    l => l.ProximityIndex),
                //widebandDiffPercent.Average(),

                AfrDiffAbsolute = (float) lines.WeightedAverage(
                    l => targetAfr - l.AfrWideband.Value, 
                    l => l.ProximityIndex), //widebandDiffAbsolute.Average(),

                NboCorrection = (float) lines.WeightedAverage(
                    l => l.AfrCorrection.Value,
                    l => l.ProximityIndex
                ),

                Count = lines.Count(),

                AvgAfr = (float)lines.WeightedAverage(
                    l => l.AfrWideband.Value,
                    l => l.ProximityIndex
                ),
                AvgKpa = lines.Average(l => l.Map.Value),
                AvgRpm = (int)lines.Average(l => l.Rpm.Value)
            };
        }
示例#2
0
 protected override Measurement AggregateMeasurements(IEnumerable<Measurement> measurements)
 {           
     return new Measurement
                {
                    X = (int)measurements.Average(m => m.X), 
                    Y = (int)measurements.Average(m => m.Y)
                };
 }
示例#3
0
 public Measurement Aggregate(IEnumerable<Measurement> measurements)
 {
     return new Measurement
                {
                    X = (int)measurements.Average(m => m.X),
                    Y = (int)measurements.Average(m => m.Y)
                };
 }
示例#4
0
        /// <summary>
        /// Gets the slope for a set of points using the formula:
        /// m = SUM(x-AVG(x)(y-AVG(y)) / SUM(x-AVG(x))^2
        /// </summary>
        /// <param name="points">Points to calculate the Slope from</param>
        /// <returns>SlopeOfPoints</returns>
        private static float SlopeOfPoints(IEnumerable<PointF> points)
        {
            float avgX = points.Average(p => p.X);
            float avgY = points.Average(p => p.Y);

            float dividend = points.Sum(p => (p.X - avgX) * (p.Y - avgY));
            float divisor = (float)points.Sum(p => Math.Pow(p.X - avgX, 2));

            return dividend / divisor;
        }
        public Measurement Aggregate(IEnumerable<Measurement> measurements)
        {
            if (measurements.Contains(null))
                throw new ArgumentNullException();

            return new Measurement()
            {
                HighValue = measurements.Average(m => m.HighValue),
                LowValue = measurements.Average(m => m.LowValue)
            };
        }
示例#6
0
 private static double Covariance(IEnumerable<double> xs, IEnumerable<double> ys)
 {
     var xAvg = xs.Average();
     var yAvg = ys.Average();
     var cov = xs.Zip(ys, (x, y) => (x - xAvg) * (y - yAvg)).Average();
     return cov;
 }
示例#7
0
        /// <summary>
        /// Calculates the statistics.
        /// </summary>
        /// <param name="benchmarks">The composite query benchmarks.</param>
        private static void CalculateStatistics(IEnumerable<BenchmarkBase> benchmarks)
        {
            if (null != benchmarks) {
                var avgSelect = benchmarks.Average(b => ((CompositeQueries)b).SimpleQuery.Time.ElapsedMilliseconds);
                Console.WriteLine("{0:0.0000} : Average simple select", avgSelect / 1000.0);

                var avgFilter = benchmarks.Average(b => ((CompositeQueries)b).FilterQuery.Time.ElapsedMilliseconds);
                Console.WriteLine("{0:0.0000} : Average simple filter", avgFilter / 1000.0);

                var avgMapReduceTags = benchmarks.Average(b => ((CompositeQueries)b).TagCountMapReduce.Time.ElapsedMilliseconds);
                Console.WriteLine("{0:0.0000} : Average Map-Reduce tags", avgMapReduceTags / 1000.0);

                var avgMapReduceComments = benchmarks.Average(b => ((CompositeQueries)b).CommentAuthorMapReduce.Time.ElapsedMilliseconds);
                Console.WriteLine("{0:0.0000} : Average Map-Reduce comments", avgMapReduceComments / 1000.0);
            }
        }
示例#8
0
        public void FillInSusiInfo(Student student, StudentInfo studentInfo, IEnumerable<CourseInfo> courseInfo)
        {
            student.FirstName = studentInfo.FirstName;
            student.LastName = studentInfo.LastName;

            Tuple<int, int> startEndYears = studentInfo.GetStartEndYear();
            Bachelor bachelor = new Bachelor
            {
                StartYear = startEndYears.Item1,
                EndYear = startEndYears.Item2,
                CurrentCourse = studentInfo.Year,
                Specialty = StudentManager.programmeMapping[studentInfo.Programme],
                Subjects = courseInfo.Select(x => x.ToSubject()).ToList(),
                CurrentAverageGrade = courseInfo.Average(x => x.Grade)
            };

            FMIEdu fmiEdu = new FMIEdu
            {
                Bachelor = bachelor,
            };

            student.FMIInfo = fmiEdu;

            db.SaveChanges();
        }
示例#9
0
 public PerfIteratorResult(IEnumerable<PerfRoundResult> resultsList)
 {
     this.ResultsList = resultsList;
     this.RepeatCount = resultsList.Count();
     this.OverallAverageTicks = resultsList.Average(r => r.AverageTicks);
     this.OverallMaxTicks = resultsList.Max(r => r.MaxTicks);
     this.OverallMinTicks = resultsList.Min(r => r.MinTicks);
 }
示例#10
0
 static double calcStdDev(IEnumerable<double> values)
 {
     double ret = 0;
     double avg = values.Average();
     double sum = values.Sum(d => Math.Pow(d - avg, 2));
     ret = Math.Sqrt((sum) / (values.Count() - 1));
     return ret;
 }
示例#11
0
        private bool AverageBool(IEnumerable<bool> itemBools)
        {
            var avgBool = itemBools.Average(i => Convert.ToDouble(i));

            var isBool = Convert.ToBoolean(Round(avgBool));

            return isBool;
        }
示例#12
0
		private int GetStandardDeviation(IEnumerable<int> values)
		{
			var setAverage = values.Average();
			var diffSqTotal = values.Sum((val) => (val - setAverage) * (val - setAverage));
			var diffSqAvg = (diffSqTotal / (values.Count() - 1));

			return (int)Math.Sqrt(diffSqAvg);
		}
示例#13
0
文件: TeamRater.cs 项目: bouwe77/fmg
        /// <summary>
        /// Gets the average rating for the given players.
        /// These players are typically all players in a specific line.
        /// </summary>
        /// <param name="players"></param>
        /// <returns></returns>
        public static decimal GetRating(IEnumerable<Player> players)
        {
            //TODO per linie de rating uitrekenen door de primary en wellicht ook secondary skills te pakken ofzoiets...

             // Nu eerst gewoon de gemiddelde rating van elke speler pakken...
             var average = players.Average(player => player.Rating);
             return average;
        }
示例#14
0
 public static FlowView Average(IEnumerable<FlowView> views)
 {
     if (views == null || !views.Any()) return null;
     var first = views.FirstOrDefault();
     return new FlowView
     {
         StatTime = first.StatTime,
         ENodebId = first.ENodebId,
         SectorId = first.SectorId,
         PdcpUplinkFlow = views.Average(x => x.PdcpUplinkFlow),
         PdcpDownlinkFlow = views.Average(x => x.PdcpDownlinkFlow),
         AverageUsers = views.Average(x => x.AverageUsers),
         MaxUsers = views.Max(x => x.MaxUsers),
         AverageActiveUsers = views.Average(x => x.AverageActiveUsers),
         MaxActiveUsers = views.Max(x => x.MaxActiveUsers)
     };
 }
示例#15
0
        public static decimal CalculatePricePerServing2(IEnumerable<Meal> meals)
        {
            if (meals == null || !meals.Any(p => p != null && p.Price != 0 && p.Servings != 0))
              {
            return -1;
              }

              return meals.Average(p => p.Servings / p.Price);
        }
示例#16
0
        private static TimedValue<DateTime, double> Average( IEnumerable<TimedValue<DateTime, double>> series )
        {
            var minTime = series.First().Time;
            var maxTime = series.Last().Time;
            double numDays = ( maxTime - minTime ).TotalDays;

            var date = minTime.AddDays( numDays / 2 );
            var price = series.Average( p => p.Value );

            return new SimplePrice( date, price );
        }
示例#17
0
 /// <summary>
 /// Factor average attack strength of multiple attackers into damage.
 /// </summary>
 /// <param name="attackStat">Attack strengths of all attackers. Usually AttackPhysical or AttackMagic.</param>
 /// <returns>New HitInfo to give to Hitbox.</returns>
 public HitInfo Attack(IEnumerable<float> attackStats)
 {
     return new HitInfo()
     {
         //damage = Mathf.CeilToInt(damage * (int)attackStats.Average() * ATTACKMODIFIER),
         damage = this.damage,
         effect = this.effect,
         knockBack = this.knockBack,
         attackStat = attackStats.Average(),
     };
 }
示例#18
0
文件: CpkMath.cs 项目: TGHGH/MesDemo
 public static double StandardDeviation(IEnumerable<double> list, double up, double low)
 {
     var average = list.Average();
     var count = list.Count();
     double t = Math.Abs(up - low);
     double u = (up + low) / 2;
     double sum = list.Sum(a => Math.Pow(a - average, 2));
     double standardDeviation = Math.Sqrt(sum / count);
     double cpk = 0;
     cpk = t / (6 * standardDeviation) * (1 - Math.Abs((average - u) * 2 / t));
     return cpk;
 }
示例#19
0
        public static double StandardDeviation(IEnumerable<double> input)
        {
            double average = input.Average();

            var helperList = new List<double>();

            for (int i = 0; i < input.Count(); i++)
            {
                helperList.Add(Math.Pow(input.ElementAt(i) - average, 2));
            }

            return Math.Sqrt((helperList.Sum() / helperList.Count()));
        }
示例#20
0
 /// <summary>
 /// Calculate the Std Devation
 /// </summary>
 /// <param name="values">List of values</param>
 /// <returns></returns>
 public static double CalculateStdDev(IEnumerable<double> values)
 {
     double ret = 0;
     if (values.Count() > 0)
     {
         //Compute the Average
         double avg = values.Average();
         //Perform the Sum of (value-avg)_2_2
         double sum = values.Sum(d => Math.Pow(d - avg, 2));
         //Put it all together
         ret = Math.Sqrt((sum) / (values.Count() - 1));
     }
     return ret;
 }
示例#21
0
文件: Program.cs 项目: tansey/poker
        /// <summary>
        /// Get variance
        /// </summary>
        public static double Variance(IEnumerable<double> data)
        {
            int len = data.Count();

            // Get average
            double avg = data.Average();

            double sum = 0;

            for (int i = 0; i < len; i++)
                sum += (data.ElementAt(i) - avg) * (data.ElementAt(i) - avg);

            return sum / (len - 1);
        }
 //A simple method to calculate the average price per piece of candy given several bags of candy
 public static decimal CalculateCandyPricePerServing(IEnumerable<BagOfCandy> bagsOfCandy)
 {
     //Rough attempt to fix several more of the issues apparent in the first table
     if(bagsOfCandy == null || !bagsOfCandy.Any(p => p != null && p.Price != 0 && p.Servings != 0))
     {
         //Return -1 for invalid results
         return -1;
     }
     else
     {
         //Attempt to average the values otherwise
         return bagsOfCandy.Average(p => p.Servings / p.Price);
     }
 }
示例#23
0
 private static double StandardDeviation(IEnumerable<double> values)
 {
     double ret = 0;
     if (values.Count() > 0)
     {
         //Compute the Average
         double avg = values.Average();
         //Perform the Sum of (value-avg)_2_2
         double sum = values.Sum(d => MathObj.Pow(d - avg, 2));
         //Put it all together
         ret = MathObj.Sqrt((sum) / (values.Count() - 1));
     }
     return ret;
 }
示例#24
0
        public PersonApiResponse GetPeopleInfo(IEnumerable<Person> personList)
        {
            PersonApiResponse response = new PersonApiResponse();
            response.NumberOfPeople = personList.Count();
            response.MaxAge = personList.Max(c=>c.Age);
            response.MinAge = personList.Min(c=>c.Age);
            response.AverageOfAge = personList.Average(c=>c.Age);

            response.NumberOfAngles = personList.Where(c => c.Race == PersonRace.Angles).Count();
            response.NumberOfAsians = personList.Where(c => c.Race == PersonRace.Asians).Count();
            response.NumberOfJutes = personList.Where(c => c.Race == PersonRace.Jutes).Count();
            response.NumberOfSaxons = personList.Where(c => c.Race == PersonRace.Saxons).Count();

            return response;
        }
示例#25
0
 private static double StandardDeviation(IEnumerable<double> values)
 {
     double ret = 0;
     if (values.Count() > 0)
     {
         var nValues = values.Count();
         if(nValues == 1) throw new ExcelErrorValueException(eErrorType.Div0);
         //Compute the Average
         double avg = values.Average();
         //Perform the Sum of (value-avg)_2_2
         double sum = values.Sum(d => MathObj.Pow(d - avg, 2));
         //Put it all together
         ret = MathObj.Sqrt((sum) / (values.Count() - 1));
     }
     return ret;
 }
 public static Skill Average(IEnumerable<Skill> skills)
 {
     return new Skill(
         skills.Average(s => s.MeanForecastingError),
         skills.Average(s => s.MeanAbsoluteError),
         skills.Average(s => s.MeanSquaredError),
         skills.Average(s => s.RootMeanSquaredError),
         skills.Average(s => s.MeanAbsolutePercentageError),
         skills.Average(s => s.RootMeanSquaredPrecentageError)
         );
 }
示例#27
0
        private CloudyType AverageCloudy(IEnumerable<CloudyType> cloudy)
        {
            var avgCloudy = cloudy.Average(i => (double)i);

            if (avgCloudy >= 0 && avgCloudy <= 12.5)
                return CloudyType.Fair;

            if (avgCloudy > 12.5 && avgCloudy <= 37.5)
                return CloudyType.PartlyCloudy;

            if (avgCloudy > 37.5 && avgCloudy <= 62.5)
                return CloudyType.Cloudy;

            if (avgCloudy > 62.5 && avgCloudy <= 87.5)
                return CloudyType.MainlyCloudy;

            if (avgCloudy > 87.5 && avgCloudy <= 100)
                return CloudyType.Overcast;

            throw new NotImplementedException();
        }
示例#28
0
文件: MathUtils.cs 项目: QANTau/QPAS
        /// <summary>
        /// Multiple linear regression. Do not include intercept column, it's added automatically.
        /// </summary>
        public static void MLR(IEnumerable<double> y, List<IEnumerable<double>> x, out double[] b, out double rSquared)
        {
            if (y.Count() <= 1)
            {
                b = Enumerable.Range(1, x.Count + 1).Select(z => 0.0).ToArray();
                rSquared = 0;
                return;
            }
            DenseMatrix yMatrix = DenseMatrix.OfColumns(y.Count(), 1, new List<IEnumerable<double>> { y });

            //insert a list of zeroes, the intercept
            x.Insert(0, Enumerable.Range(0, x[0].Count()).Select(z => 1.0).ToList());

            DenseMatrix xMatrix = DenseMatrix.OfColumns(x[0].Count(), x.Count, x);

            var p = xMatrix.QR().Solve(yMatrix);

            double yAvg = y.Average();
            double ssReg = (xMatrix * p).Column(0).Sum(f => (f - yAvg) * (f - yAvg));
            double ssTotal = y.Sum(yVal => (yVal - yAvg) * (yVal - yAvg));

            rSquared = ssReg / ssTotal;
            b = p.Column(0).ToArray();
        }
 private object SwitchType(IEnumerable<object> items) {
     switch (_outType) {
         case "decimal":
             return items.Average(x => Convert.ToDecimal(x));
         case "double":
             return items.Average(x => Convert.ToDouble(x));
         case "float":
             return items.Average(x => Convert.ToSingle(x));
         case "single":
             return items.Average(x => Convert.ToSingle(x));
         case "int32":
             return items.Average(x => Convert.ToInt32(x));
         case "int64":
             return items.Average(x => Convert.ToInt64(x));
         default:
             Logger.EntityWarn(EntityName, "Unable to handle average of type {0}", _outType);
             return 0;
     }
 }
示例#30
0
 private static double GetAvgPriceMinus50PercentageOfAverage(IEnumerable <CompetitorProduct> compProducts)
 {
     return(compProducts.Average(cpForAverage => cpForAverage.Price) - FiftyPercentageOfAveragePrice(compProducts));
 }
示例#31
0
        static void Main(string[] args)
        {
            //Obtener el promedio de todos los números mayores a 50.

            List <Operacion> numeros = new List <Operacion>();
            var seed   = Environment.TickCount;
            var random = new Random(seed);

            for (int i = 0; i < 50; i++)
            {
                numeros.Add(new Operacion(random.Next(0, 100)));
            }

            Console.WriteLine("Lista de números");
            foreach (var item in numeros)
            {
                Console.WriteLine("{0}", item.Numero);
            }
            Console.WriteLine();

            IEnumerable <Operacion> mayoresA50 =
                (numeros.Where(x => x.Numero > 50));

            Console.WriteLine("******Promedio de los números mayores a 50 son:******");
            Console.WriteLine(mayoresA50.Average(x => x.Numero));
            Console.WriteLine();


            //Contar en la lista la cantidad de números pares e impares.
            //Este problema debe resolverse en una sentencia o en una sola consulta.

            IEnumerable <Operacion> listaPar =
                numeros.Where(x => x.Numero % 2 == 0);

            Console.WriteLine("******Cantidad de números pares son:******");
            Console.WriteLine(listaPar.Count());
            Console.WriteLine();
            Console.WriteLine("******Cantidad de números impares son:******");
            Console.WriteLine(numeros.Count() - listaPar.Count());
            Console.WriteLine();

            //Mostrar por consola cada elemento y la cantidad de veces que se repite en la lista.
            int contador = 0;

            Console.WriteLine("******Números y cantidad de veces que se repiten:******");
            foreach (var item in numeros)
            {
                int cont = 0;
                for (int i = 0; i < 1; i++)
                {
                    foreach (var num in numeros)
                    {
                        if (item.Numero == num.Numero)
                        {
                            cont++;
                        }
                    }
                }
                Console.WriteLine("{0}", item.Numero + "---" + cont);
            }
            Console.WriteLine();
            Console.ReadKey();
        }
示例#32
0
 public override void ConfigureParameters(IEnumerable <double> data)
 {
     OriginalStandardDeviation = data.StandardDeviation();
     OriginalMean = data.Average();
 }
示例#33
0
        public static double StandardDeviation(IEnumerable <double> values)
        {
            double avg = values.Average();

            return(Math.Sqrt(values.Average(v => Math.Pow(v - avg, 2))));
        }
示例#34
0
        private void CalculateResult(IEnumerable <TimeSpan> values, Type targetType)
        {
            TimeSpan result;

            switch (ReductionOperation.ActualValue.Value)
            {
            case ReductionOperations.Sum:
                result = values.Aggregate(new TimeSpan(), (x, y) => x + y);
                break;

            case ReductionOperations.Min:
                result = values.Min();
                break;

            case ReductionOperations.Max:
                result = values.Max();
                break;

            case ReductionOperations.Avg:
                result = TimeSpan.FromMilliseconds(values.Average(x => x.TotalMilliseconds));
                break;

            case ReductionOperations.Assign:
                result = values.Last();
                break;

            default:
                throw new InvalidOperationException(string.Format("Operation {0} is not supported as ReductionOperation for type: {1}.", ReductionOperation.ActualValue.Value, targetType));
            }

            TimeSpanValue target;

            switch (TargetOperation.ActualValue.Value)
            {
            case ReductionOperations.Sum:
                target        = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, new TimeSpan());
                target.Value += result;
                break;

            case ReductionOperations.Min:
                target       = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, TimeSpan.MaxValue);
                target.Value = target.Value < result ? target.Value : result;
                break;

            case ReductionOperations.Max:
                target       = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, TimeSpan.MinValue);
                target.Value = target.Value > result ? target.Value : result;
                break;

            case ReductionOperations.Avg:
                target       = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, result);
                target.Value = TimeSpan.FromMilliseconds((target.Value.TotalMilliseconds + result.TotalMilliseconds) / 2);
                break;

            case ReductionOperations.Assign:
                target       = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, new TimeSpan());
                target.Value = result;
                break;

            default:
                throw new InvalidOperationException(string.Format("Operation {0} is not supported as TargetOperation for type: {1}.", TargetOperation.ActualValue.Value, targetType));
            }
        }
示例#35
0
 public static long AverageValue(this IEnumerable <long> values)
 {
     return((long)values.Average());
 }
示例#36
0
 public static double AverageValue(this IEnumerable <double> values)
 {
     return(values.Average());
 }
 ///<summary>Returns the average of the timespans</summary>
 public static TimeSpan Average(this IEnumerable <TimeSpan> @this)
 {
     return(@this.Average(currentTimeSpan => currentTimeSpan.TotalMilliseconds).Milliseconds());
 }
示例#38
0
 public static int AverageValue(this IEnumerable <int> values)
 {
     return((int)values.Average());
 }
示例#39
0
 private double CalculateAverage(IEnumerable <AmountOfGuesses> amountOfGuesses)
 {
     return(amountOfGuesses.Average(guess => guess.AmountOfGuessesNeeded));
 }
示例#40
0
        private void CalculateResult(IEnumerable <double> values, Type targetType)
        {
            double result;

            switch (ReductionOperation.ActualValue.Value)
            {
            case ReductionOperations.Sum:
                result = values.Sum();
                break;

            case ReductionOperations.Product:
                result = values.Aggregate(1.0, (x, y) => x * y);
                break;

            case ReductionOperations.Count:
                result = values.Count();
                break;

            case ReductionOperations.Min:
                result = values.Min();
                break;

            case ReductionOperations.Max:
                result = values.Max();
                break;

            case ReductionOperations.Avg:
                result = values.Average();
                break;

            case ReductionOperations.Assign:
                result = values.Last();
                break;

            default:
                throw new InvalidOperationException(string.Format("Operation {0} is not supported as ReductionOperation for type: {1}.", ReductionOperation.ActualValue.Value, targetType));
            }

            DoubleValue target;

            switch (TargetOperation.ActualValue.Value)
            {
            case ReductionOperations.Sum:
                target        = InitializeTarget <DoubleValue, double>(targetType, 0.0);
                target.Value += result;
                break;

            case ReductionOperations.Product:
                target       = InitializeTarget <DoubleValue, double>(targetType, 1.0);
                target.Value = target.Value * result;
                break;

            case ReductionOperations.Min:
                target       = InitializeTarget <DoubleValue, double>(targetType, double.MaxValue);
                target.Value = Math.Min(target.Value, result);
                break;

            case ReductionOperations.Max:
                target       = InitializeTarget <DoubleValue, double>(targetType, double.MinValue);
                target.Value = Math.Max(target.Value, result);
                break;

            case ReductionOperations.Avg:
                target       = InitializeTarget <DoubleValue, double>(targetType, result);
                target.Value = (target.Value + result) / 2.0;
                break;

            case ReductionOperations.Assign:
                target       = InitializeTarget <DoubleValue, double>(targetType, 0.0);
                target.Value = result;
                break;

            default:
                throw new InvalidOperationException(string.Format("Operation {0} is not supported as TargetOperation for type: {1}.", TargetOperation.ActualValue.Value, targetType));
            }
        }
        public static float[] GetFeatures(TextBlock textBlock, IEnumerable <PdfPath> paths, IEnumerable <IPdfImage> images,
                                          double averagePageFontHeight, double bboxArea, List <DocumentBookmarkNode> pageBookmarksNodes)
        {
            // text block features
            float blockAspectRatio = float.NaN;

            // Letters features
            float charsCount           = 0;
            float pctNumericChars      = 0;
            float pctAlphabeticalChars = 0;
            float pctSymbolicChars     = 0;
            float pctBulletChars       = 0;
            float deltaToHeight        = float.NaN; // might be problematic

            float wordsCount           = 0;
            float linesCount           = 0;
            float bestNormEditDistance = float.NaN;

            if (textBlock?.TextLines != null && textBlock.TextLines.Any())
            {
                blockAspectRatio = (float)Math.Round(textBlock.BoundingBox.Width / textBlock.BoundingBox.Height, 5);

                var avgHeight = averagePageFontHeight;

                var    textLines = textBlock.TextLines;
                var    words     = textLines.SelectMany(tl => tl.Words).ToList();
                var    letters   = words.SelectMany(w => w.Letters).ToList();
                char[] chars     = letters.SelectMany(l => l.Value).ToArray();

                charsCount           = chars.Length;
                pctNumericChars      = (float)Math.Round(chars.Count(c => char.IsNumber(c)) / charsCount, 5);
                pctAlphabeticalChars = (float)Math.Round(chars.Count(c => char.IsLetter(c)) / charsCount, 5);
                pctSymbolicChars     = (float)Math.Round(chars.Count(c => !char.IsLetterOrDigit(c)) / charsCount, 5);
                pctBulletChars       = (float)Math.Round(chars.Count(c => Bullets.Any(bullet => bullet == c)) / charsCount, 5);
                if (avgHeight != 0)
                {
                    deltaToHeight = (float)Math.Round(letters.Select(l => l.GlyphRectangle.Height).Average() / avgHeight, 5);
                }

                wordsCount = words.Count();
                linesCount = textLines.Count();

                if (pageBookmarksNodes != null)
                {
                    // http://www.unicode.org/reports/tr15/
                    var textBlockNormalised = textBlock.Text.Normalize(NormalizationForm.FormKC).ToLower();
                    foreach (var bookmark in pageBookmarksNodes)
                    {
                        // need to normalise both text
                        var bookmarkTextNormalised = bookmark.Title.Normalize(NormalizationForm.FormKC).ToLower();
                        var currentDist            = Distances.MinimumEditDistanceNormalised(textBlockNormalised, bookmarkTextNormalised);
                        if (float.IsNaN(bestNormEditDistance) || currentDist < bestNormEditDistance)
                        {
                            bestNormEditDistance = (float)Math.Round(currentDist, 5);
                        }
                    }
                }
            }

            // Paths features
            float pathsCount     = 0;
            float pctBezierPaths = 0;
            float pctHorPaths    = 0;
            float pctVertPaths   = 0;
            float pctOblPaths    = 0;

            if (paths != null && paths.Count() > 0)
            {
                foreach (var path in paths)
                {
                    foreach (var command in path.Commands)
                    {
                        if (command is BezierCurve bezierCurve)
                        {
                            pathsCount++;
                            pctBezierPaths++;
                        }
                        else if (command is Line line)
                        {
                            pathsCount++;
                            if (line.From.X == line.To.X)
                            {
                                pctVertPaths++;
                            }
                            else if (line.From.Y == line.To.Y)
                            {
                                pctHorPaths++;
                            }
                            else
                            {
                                pctOblPaths++;
                            }
                        }
                    }
                }

                pctBezierPaths = (float)Math.Round(pctBezierPaths / pathsCount, 5);
                pctHorPaths    = (float)Math.Round(pctHorPaths / pathsCount, 5);
                pctVertPaths   = (float)Math.Round(pctVertPaths / pathsCount, 5);
                pctOblPaths    = (float)Math.Round(pctOblPaths / pathsCount, 5);
            }

            // Images features
            float imagesCount        = 0;
            float imageAvgProportion = 0;

            if (images != null && images.Count() > 0)
            {
                imagesCount        = images.Count();
                imageAvgProportion = (float)(images.Average(i => i.Bounds.Area) / bboxArea);
            }

            return(new float[]
            {
                blockAspectRatio, charsCount, wordsCount, linesCount, pctNumericChars,
                pctAlphabeticalChars, pctSymbolicChars, pctBulletChars, deltaToHeight,
                pathsCount, pctBezierPaths, pctHorPaths, pctVertPaths, pctOblPaths,
                imagesCount, imageAvgProportion, bestNormEditDistance
            });
        }
示例#42
0
        /***************************************************/
        /**** public Methods - Vectors                  ****/
        /***************************************************/

        public static Line FitLine(this IEnumerable <Point> points, double tolerance = Tolerance.Distance)
        {
            // Based on https://www.scribd.com/doc/31477970/Regressions-et-trajectoires-3D

            int n = points.Count();

            if (n < 2)
            {
                return(null);
            }

            Point C = points.Average();

            double xx = 0.0; double xy = 0.0; double xz = 0.0;
            double yy = 0.0; double yz = 0.0; double zz = 0.0;

            foreach (Point P in points)
            {
                xx += P.X * P.X;
                xy += P.X * P.Y;
                xz += P.X * P.Z;
                yy += P.Y * P.Y;
                yz += P.Y * P.Z;
                zz += P.Z * P.Z;
            }

            double Sxx = xx / n - C.X * C.X;
            double Sxy = xy / n - C.X * C.Y;
            double Sxz = xz / n - C.X * C.Z;
            double Syy = yy / n - C.Y * C.Y;
            double Syz = yz / n - C.Y * C.Z;
            double Szz = zz / n - C.Z * C.Z;

            double theta  = Math.Atan(2 * Sxy / (Sxx - Syy)) * 0.5;
            double stheta = Math.Sin(theta);
            double ctheta = Math.Cos(theta);
            double K11    = (Syy + Szz) * ctheta * ctheta + (Sxx + Szz) * stheta * stheta - 2 * Sxy * ctheta * stheta;
            double K22    = (Syy + Szz) * stheta * stheta + (Sxx + Szz) * ctheta * ctheta + 2 * Sxy * ctheta * stheta;
            double K12    = -Sxy * (ctheta * ctheta - stheta * stheta) + (Sxx - Syy) * ctheta * stheta;
            double K10    = Sxz * ctheta + Syz * stheta;
            double K01    = -Sxz * stheta + Syz * ctheta;
            double K00    = Sxx + Syy;

            double c0 = K01 * K01 * K11 + K10 * K10 * K22 - K00 * K11 * K22;
            double c1 = K00 * K11 + K00 * K22 + K11 * K22 - K01 * K01 - K10 * K10;
            double c2 = -K00 - K11 - K22;

            double p = c1 - c2 * c2 / 3;
            double q = c2 * c2 * c2 * 2 / 27 - c1 * c2 / 3 + c0;
            double R = q * q * 0.25 + p * p * p / 27;

            double sqrDeltaM;
            double cc = -c2 / 3;

            if (R > tolerance)
            {
                sqrDeltaM = cc + Math.Pow(-q * 0.5 + Math.Sqrt(R), 1.0 / 3.0) + Math.Pow(-q * 0.5 - Math.Sqrt(R), 1.0 / 3.0);
            }
            else
            {
                double rho           = Math.Sqrt(-p * p * p / 27);
                double fi            = Math.Acos(-q / rho * 0.5);
                double doubleRhoRoot = 2 * Math.Pow(rho, 1.0 / 3.0);
                double minCos        = Math.Min(Math.Cos(fi / 3), Math.Min(Math.Cos((fi + 2 * Math.PI) / 3), Math.Cos((fi + 4 * Math.PI))));
                sqrDeltaM = cc + doubleRhoRoot * minCos;
            }

            double a = -K10 / (K11 - sqrDeltaM) * ctheta + K01 / (K22 - sqrDeltaM) * stheta;
            double b = -K10 / (K11 - sqrDeltaM) * stheta - K01 / (K22 - sqrDeltaM) * ctheta;
            double u = ((1 + b * b) * C.X - a * b * C.Y + a * C.Z) / (1 + a * a + b * b);
            double v = (-a * b * C.X + (1 + a * a) * C.Y + b * C.Z) / (1 + a * a + b * b);
            double w = (a * C.X + b * C.Y + (a * a + b * b) * C.Z) / (1 + a * a + b * b);

            Point H = new Point {
                X = u, Y = v, Z = w
            };

            return(new Line {
                Start = C + (C - H), End = H
            });
        }
示例#43
0
        internal static IGun CreateBenchmarkGun(string key, TankObjectKey ownerKey, IEnumerable <IGun> guns)
        {
            var benchmark = new VirtualGun();

            benchmark.Key      = key;
            benchmark.OwnerKey = ownerKey;
            BenchmarkDamageableModule.Initialize(benchmark, guns);
            benchmark.Accuracy   = guns.Average(g => g.Accuracy);
            benchmark.AimingTime = guns.Average(g => g.AimingTime);
            benchmark.GunArmor   = guns.Average(g => g.GunArmor);

            var burstGuns = guns.Where(g => g.Burst != null);

            if (burstGuns.Count() == 0)
            {
                benchmark.Burst = null;
            }
            else
            {
                benchmark.Burst = new Burst((int)burstGuns.Average(g => g.Burst.Count), burstGuns.Average(g => g.Burst.Rate));
            }

            benchmark.CamouflageFactorAfterShot = guns.Average(g => g.CamouflageFactorAfterShot);

            var clipGuns = guns.Where(g => g.Clip != null);

            if (clipGuns.Count() == 0)
            {
                benchmark.Clip = null;
            }
            else
            {
                benchmark.Clip = new Clip((int)clipGuns.Average(g => g.Clip.Count), clipGuns.Average(g => g.Clip.Rate));
            }

            benchmark.HorizontalTraverse = new HorizontalTraverse(guns.Median(g => g.HorizontalTraverse.Left), guns.Median(g => g.HorizontalTraverse.Right));
            benchmark.MaxAmmo            = (int)guns.Average(g => g.MaxAmmo);
            benchmark.ReloadTime         = guns.Average(g => g.ReloadTime);
            benchmark.RotationSpeed      = guns.Average(g => g.RotationSpeed);
            benchmark.ShotDispersion     = new TurretShotDispersion(guns.Average(g => g.ShotDispersion.AfterShot), guns.Average(g => g.ShotDispersion.TurretRotation), guns.Average(g => g.ShotDispersion.GunDamaged));

            var shellGroups = new List <KeyValuePair <IGun, IShell> > [4];

            for (int i = 0; i < 4; ++i)
            {
                shellGroups[i] = new List <KeyValuePair <IGun, IShell> >();
            }

            foreach (var gun in guns)
            {
                foreach (var shell in gun.Shots)
                {
                    var kineticFlag = shell.Type.IsKineticShellType() ? 2 : 0;
                    var premiumFlag = shell.CurrencyType == CurrencyType.Gold ? 1 : 0;
                    shellGroups[kineticFlag | premiumFlag].Add(new KeyValuePair <IGun, IShell>(gun, shell));
                }
            }

            int shellIndex = 0;
            var shots      = new List <IShell>();

            foreach (var shellGroup in shellGroups.Where(g => g.Count > 0))
            {
                var shellKey       = $"{key}Shell{shellIndex++}";
                var benchmarkShell = BenchmarkShell.Create(shellKey, shellGroup.Select(g => g.Value));
                benchmarkShell.DamagePerMinute = shellGroup.Average(g => VirtualGun.CalculateDpm(g.Key, g.Value));
                shots.Add(benchmarkShell);
            }

            benchmark.Shots = shots.ToArray();

            benchmark.VerticalTraverse = new GunVerticalTraverse();
            benchmark.VerticalTraverse.DefaultPitchLimits = new PitchLimits(guns.Average(g => g.VerticalTraverse.Front.Elevation), guns.Average(g => g.VerticalTraverse.Front.Depression));
            return(benchmark);
        }
示例#44
0
 /// <summary>
 ///     Arithmetischer Mittelwert, Durchschnitt
 /// </summary>
 /// <param name="list"></param>
 /// <returns></returns>
 public static double Mean(this IEnumerable <double> list)
 {
     return(list.Average()); // :-)
 }
示例#45
0
 private static double FiftyPercentageOfAveragePrice(IEnumerable <CompetitorProduct> compProducts)
 {
     return(compProducts.Average(cpForAverage => cpForAverage.Price) * 50 / 100);
 }
示例#46
0
文件: Program.cs 项目: octwanna/BoSSS
        protected override double RunSolverOneStep(int TimestepNo, double phystime, double dt)
        {
            Stopwatch globalWatch = new Stopwatch();

            globalWatch.Start();

            /*
             * Configuration options
             */
            // Only applies to subdivision-based quadrature (brute force and adaptive)
            int[] divisions = new int[] { (int)testCase.GridSize };

            // Only applies to adaptive quadrature
            int leafDivisions = -1;

            // Only applies to regularized quadrature
            double[] widths                = new double[] { double.NaN };
            int[]    vanishingMonents      = new int[] { int.MinValue };
            int[]    continuousDerivatives = new int[] { int.MinValue };

            // Only applies to HMF quadrature
            LineSegment.IRootFindingAlgorithm rootFindingAlgorithm;



            /*
             * ENTER CONFIGURATION HERE
             */

            // Export options
            int  plotSuperSampling           = -1;
            bool logVolumeNodes              = false;
            int  logVolumeNodes_selectedCell = -1;
            bool logSurfaceNodes             = false;
            bool logConsole    = false;
            int  selectedShift = -1;

            // Quadrature variant

            Modes mode = Modes.EquivalentPolynomials;

            int[] orders = new int[] { 1, 2 };

            //Modes mode = Modes.HMFClassic;
            //int[] orders = new int[] { 3, 4, 5, 6, 7, 8 };
            //LevelSetSurfaceQuadRuleFactory.RestrictNodes = false;
            //LevelSetSurfaceQuadRuleFactory.UseGaussNodes = true;
            //LevelSetVolumeQuadRuleFactory.RestrictNodes = false;
            //LevelSetVolumeQuadRuleFactory.UseGaussNodes = true;
            //LevelSetVolumeQuadRuleFactory.NodeCountSafetyFactor = 1.0;

            //Modes mode = Modes.HMFClassic;
            //int[] orders = new int[] { 1 };
            //LevelSetSurfaceQuadRuleFactory.RestrictNodes = false;
            //LevelSetSurfaceQuadRuleFactory.UseGaussNodes = true;
            //LevelSetVolumeQuadRuleFactory.RestrictNodes = false;
            //LevelSetVolumeQuadRuleFactory.UseGaussNodes = true;
            //LevelSetVolumeQuadRuleFactory.NodeCountSafetyFactor = 1.0;

            //Modes mode = Modes.HMFOneStepGaussAndStokes;
            //int[] orders = new int[] { 2, 4, 6, 8, 10 };

            //Modes mode = Modes.Adaptive;
            //int[] orders = new int[] { 1 };
            //int[] divisions = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
            //int leafDivisions = 1;

            //Modes mode = Modes.Regularized;
            //int[] orders = Enumerable.Range(1, 20).Select(k => 2 * k - 1).ToArray();
            //widths = new double[] { 0.1, 0.2 };
            //vanishingMonents = new int[] { 0, 2, 4, 6 };
            //continuousDerivatives = new int[] { 1, 3, 5 };

            //Modes mode = Modes.BruteForce;
            //int[] orders = new int[] { 1 };
            //divisions = new int[] { 0, 1, 2, 3, 4 };

            //Modes mode = Modes.Standard;
            //int[] orders = Enumerable.Range(1, 20).Select(k => 2 * k - 1).ToArray();

            if (levelSet is IAnalyticLevelSet)
            {
                rootFindingAlgorithm = new AnalyticLevelSetRootFindingAlgorithm();
            }
            else
            {
                rootFindingAlgorithm = new LineSegment.SafeGuardedNewtonMethod(1e-14);
                //rootFindingAlgorithm = new LineSegment.GSLRootFindingAlgorithm(1e-14);
            }

            /*
             * END OF CONFIGURATION
             */


            SubGrid  cutCellGrid     = levelSetTracker.Regions.GetCutCellSubGrid();
            CellMask cellMask        = CellMask.GetFullMask(GridData);
            SubGrid  selectedSubGrid = new SubGrid(cellMask);

            testCase.ScaleShifts(0.5 * testCase.GridSpacing);
            double hBase = GridData.Cells.h_maxGlobal;

            string logName = ""
                             + testCase.GetType().Name
                             + "_" + Grid.RefElements[0].GetType().Name
                             + "_" + testCase.GridSize
                             + "_" + mode.ToString();

            if (logConsole)
            {
                string filename = logName + "_stdout.txt";
                ilPSP.Environment.StdOut.WriterS.Add(new StreamWriter(filename));
            }

            Console.WriteLine("Test case: " + testCase.GetType().Name);

            var errorMap = new Dictionary <Tuple <int, int, double, int, int>, List <Tuple <double, double, int> > >();

            foreach (int division in divisions)
            {
                foreach (int order in orders)
                {
                    foreach (double width in widths)
                    {
                        foreach (int vanishingMoment in vanishingMonents)
                        {
                            foreach (int continuousDerivative in continuousDerivatives)
                            {
                                errorMap[Tuple.Create(division, order, width, vanishingMoment, continuousDerivative)] =
                                    new List <Tuple <double, double, int> >();
                            }
                        }
                    }
                }
            }

            int i = 1;

            while (testCase.ProceedToNextShift())
            {
                Console.WriteLine("Processing shift " + i + " of " + testCase.NumberOfShifts);

                if (selectedShift > 0 && i != selectedShift)
                {
                    i++;
                    continue;
                }

                cutCellGrid = new SubGrid(
                    levelSetTracker.Regions.GetCutCellSubGrid().VolumeMask.Intersect(
                        selectedSubGrid.VolumeMask));

                double referenceValue = SetUpConfiguration();

                StreamWriter volumeNodesLog  = null;
                StreamWriter surfaceNodesLog = null;
                if (plotSuperSampling >= 0)
                {
                    PlotCurrentState(0.0, 0, plotSuperSampling, cutCellGrid);
                }

                Console.WriteLine();
                foreach (int division in divisions)
                {
                    Console.WriteLine("Number of divisions: " + division);

                    if (logVolumeNodes)
                    {
                        string filename = Path.Combine(
                            Path.GetFullPath("."),
                            "volumeNodes_" + testCase.GetType().Name + "_" + i + "_" + division);
                        volumeNodesLog = new StreamWriter(filename + ".txt");
                        if (GridData.SpatialDimension == 2)
                        {
                            volumeNodesLog.WriteLine("Cell\tNode\tx\ty\tweight");
                        }
                        else
                        {
                            volumeNodesLog.WriteLine("Cell\tNode\tx\ty\tz\tweight");
                        }
                    }

                    if (logSurfaceNodes)
                    {
                        string filename = Path.Combine(
                            Path.GetFullPath("."),
                            "surfaceNodes_" + testCase.GetType().Name + "_" + i + "_" + division);
                        surfaceNodesLog = new StreamWriter(filename + ".txt");
                        if (Grid.SpatialDimension == 2)
                        {
                            surfaceNodesLog.WriteLine("Cell\tNode\tx\ty\tweight");
                        }
                        else
                        {
                            surfaceNodesLog.WriteLine("Cell\tNode\tx\ty\tz\tweight");
                        }
                    }

                    foreach (int order in orders)
                    {
                        Console.WriteLine("Order: " + order);

                        foreach (double width in widths)
                        {
                            foreach (int vanishingMoment in vanishingMonents)
                            {
                                foreach (int continuousDerivative in continuousDerivatives)
                                {
                                    var result = PerformConfiguration(
                                        mode,
                                        order,
                                        division,
                                        volumeNodesLog,
                                        surfaceNodesLog,
                                        leafDivisions,
                                        vanishingMoment,
                                        continuousDerivative,
                                        width,
                                        hBase,
                                        rootFindingAlgorithm,
                                        logVolumeNodes_selectedCell);
                                    double error = Math.Abs(result.Item1 - referenceValue);

                                    var key = Tuple.Create(
                                        division, order, width, vanishingMoment, continuousDerivative);
                                    errorMap[key].Add(Tuple.Create(
                                                          result.Item1 + testCase.Solution - referenceValue,
                                                          error,
                                                          result.Item2));
                                }
                            }
                        }
                    }

                    if (volumeNodesLog != null)
                    {
                        volumeNodesLog.Close();
                    }
                    if (surfaceNodesLog != null)
                    {
                        surfaceNodesLog.Close();
                    }
                }
                Console.WriteLine();

                i++;
            }
            testCase.ResetShifts();

            using (StreamWriter log = new StreamWriter(logName + ".txt")) {
                log.WriteLine("Divisions\tOrder\tWidth\tMoments\tDerivatives\tResult\tMeanError\tMeanRelError\tStdDev\tMinError\tMaxError\tMaxErrorCase\tTime");

                foreach (var entry in errorMap)
                {
                    if (entry.Value.Count == 0)
                    {
                        continue;
                    }

                    IEnumerable <double> errors = entry.Value.Select((tuple) => tuple.Item2);
                    double meanResult           = entry.Value.Select(tuple => tuple.Item1).Average();
                    double meanError            = errors.Average();
                    double stdDev = Math.Sqrt(errors.Select((error) => error * error).Average() - meanError * meanError);
                    double time   = entry.Value.Select((tuple) => tuple.Item3).Average();

                    string line = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}",
                                                entry.Key.Item1, // division
                                                entry.Key.Item2, // order
                                                entry.Key.Item3, // width
                                                entry.Key.Item4, // vanishing moments
                                                entry.Key.Item5, // continuous derivative
                                                meanResult.ToString(formatInfo),
                                                meanError.ToString(formatInfo),
                                                (meanError / testCase.Solution).ToString(formatInfo),
                                                stdDev.ToString(formatInfo),
                                                errors.Min().ToString(formatInfo),
                                                errors.Max().ToString(formatInfo),
                                                errors.IndexOfMax((d) => d) + 1,
                                                time.ToString(formatInfo));


                    log.WriteLine(line);
                }
            }

            globalWatch.Stop();
            Console.WriteLine("Finished case " + testCase.GetType().Name + " after " + globalWatch.ElapsedMilliseconds + "ms");

            return(dt);
        }
示例#47
0
 public static decimal AverageValue(this IEnumerable <decimal> values)
 {
     return(values.Average());
 }
        public StatisticsModel()
        {
            orderRepository = new OrderRepository();
            orderRepository.Initialize();
            userRepository = new AppUserRepository();
            userRepository.Initialize();
            furnitureRepository = new FurnitureRepository();
            furnitureRepository.Initialize();
            categoryRepository = new CategoryRepository();
            categoryRepository.Initialize();
            manufacturerRepository = new ManufacturerRepository();
            manufacturerRepository.Initialize();
            //
            //
            AppUserTotalStats = orderRepository.Items.GroupBy(oh => new { ID = oh.AppUserID, Name = oh.AppUser.Name })
                                .Select(g => new AppUserTotal(g.Key.ID, g.Key.Name, g.Sum(oh => oh.GetSum())))
                                .OrderByDescending(ut => ut.Total);
            //
            IEnumerable <int> totals = orderRepository.Items
                                       .Where(oh => oh.Date != null)
                                       .Select(oh => (int)oh.GetSum());

            ReceiptStats = (totals.Min(), (int)totals.Average(), totals.Max());
            //
            categoryManufacturerAverage = new Dictionary <string, Dictionary <string, List <decimal> > >();
            furnitureRepository.Items.ForEach(f => {
                if (categoryManufacturerAverage.ContainsKey(f.Category.Name))
                {
                    if (categoryManufacturerAverage[f.Category.Name].ContainsKey(f.Manufacturer.Name))
                    {
                        categoryManufacturerAverage[f.Category.Name][f.Manufacturer.Name].Add(f.Price);
                    }
                    else
                    {
                        categoryManufacturerAverage[f.Category.Name][f.Manufacturer.Name] = new List <decimal>();
                        categoryManufacturerAverage[f.Category.Name][f.Manufacturer.Name].Add(f.Price);
                    }
                }
                else
                {
                    categoryManufacturerAverage[f.Category.Name] = new Dictionary <string, List <decimal> >();
                    categoryManufacturerAverage[f.Category.Name][f.Manufacturer.Name] = new List <decimal>();
                    categoryManufacturerAverage[f.Category.Name][f.Manufacturer.Name].Add(f.Price);
                }
            });
            //
            foreach (var oh in orderRepository.Items)
            {
                if (oh.Date == null)
                {
                    continue;
                }
                //
                DateTime date           = ((DateTime)oh.Date).Date;
                int      numberOfOrders = 1;
                if (ordersByDate.ContainsKey(date))
                {
                    numberOfOrders += ordersByDate[date];
                }
                ordersByDate[date] = numberOfOrders;
                //
                oh.OrderDetails.ForEach(od =>
                {
                    int bought = od.Quantity;
                    if (furnitureBought.ContainsKey(od.VendorCode))
                    {
                        bought += furnitureBought[od.VendorCode];
                    }
                    furnitureBought[od.VendorCode] = bought;
                });
            }
        }
示例#49
0
 public static decimal Average(IEnumerable <decimal> source)
 {
     return(source.Average());
 }
示例#50
0
 public void Int(IEnumerable <int> source, double expected)
 {
     Assert.Equal(expected, source.Average());
     Assert.Equal(expected, source.Average(x => x));
 }
示例#51
0
 public static float AverageValue(this IEnumerable <float> values)
 {
     return(values.Average());
 }
示例#52
0
        async Task LoopTraceEventOutput()
        {
            try
            {
                while (TaskCheckLoop(vTask_TraceEventOutput))
                {
                    try
                    {
                        //Check the total available frames and last added frame time
                        int  TotalFrameTimes   = vListFrameTime.Count;
                        bool SkipCurrentFrames = (GetSystemTicksMs() - vLastFrameTimeAdded) >= 1000;
                        if (SkipCurrentFrames || TotalFrameTimes <= 0)
                        {
                            AVActions.ActionDispatcherInvoke(delegate
                            {
                                stackpanel_CurrentFps.Visibility = Visibility.Collapsed;
                            });

                            continue;
                        }

                        //Reverse the frames list
                        IEnumerable <double> ReversedFrameList = vListFrameTime.AsEnumerable().Reverse();

                        //Calculate the current fps
                        double CurrentFrameTimes      = ReversedFrameList.Take(100).Average(); //1sec
                        int    CurrentFramesPerSecond = Convert.ToInt32(1000 / CurrentFrameTimes);

                        //Calculate the average fps
                        double AverageFrameTimes      = ReversedFrameList.Average();
                        int    AverageFramesPerSecond = Convert.ToInt32(1000 / AverageFrameTimes);

                        //Convert fps to string
                        string StringCurrentFramesPerSecond = string.Empty;
                        if (Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "FpsShowCurrentFps")))
                        {
                            StringCurrentFramesPerSecond = " " + CurrentFramesPerSecond.ToString() + "FPS";
                        }
                        string StringCurrentFrameTimes = string.Empty;
                        if (Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "FpsShowCurrentLatency")))
                        {
                            StringCurrentFrameTimes = " " + CurrentFrameTimes.ToString("0.00") + "MS";
                        }
                        string StringAverageFramesPerSecond = string.Empty;
                        if (Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "FpsShowAverageFps")))
                        {
                            StringAverageFramesPerSecond = " " + AverageFramesPerSecond.ToString() + "AVG";
                        }

                        //Update the fps counter
                        Debug.WriteLine("(" + vTargetProcess.Identifier + ") MS" + CurrentFrameTimes.ToString("0.00") + " / FPS " + CurrentFramesPerSecond + " / AVG " + AverageFramesPerSecond);
                        string StringDisplay = AVFunctions.StringRemoveStart(vTitleFPS + StringCurrentFramesPerSecond + StringCurrentFrameTimes + StringAverageFramesPerSecond, " ");

                        if (!string.IsNullOrWhiteSpace(StringDisplay))
                        {
                            AVActions.ActionDispatcherInvoke(delegate
                            {
                                textblock_CurrentFps.Text        = StringDisplay;
                                stackpanel_CurrentFps.Visibility = Visibility.Visible;
                            });
                        }
                        else
                        {
                            AVActions.ActionDispatcherInvoke(delegate
                            {
                                stackpanel_CurrentFps.Visibility = Visibility.Collapsed;
                            });
                        }
                    }
                    catch { }
                    finally
                    {
                        //Delay the loop task
                        await TaskDelayLoop(1000, vTask_TraceEventOutput);
                    }
                }
            }
            catch { }
        }
示例#53
0
 private static string GetSeriesAverage(IEnumerable <int> numbers) => numbers?.Average().ToString(CultureInfo.InvariantCulture);
示例#54
0
 public static int Mean(this IEnumerable <int> current)
 {
     return((int)current.Average());
 }
示例#55
0
 public static float Mean(this IEnumerable <float> current)
 {
     return((float)current.Average());
 }
示例#56
0
        private void ProcessMeasurement(Meter meter, StepChangeMeasurement measurement, string historianServer, string historianInstance, DateTime startTime, DateTime endTime)
        {
            using (DataContext dataContext = new DataContext("systemSettings"))
                using (Historian historian = new Historian(historianServer, historianInstance))
                {
                    PQMeasurement  pqMeasurement = dataContext.Table <PQMeasurement>().QueryRecordWhere("ID = {0}", measurement.PQMeasurementID);
                    Channel        channel       = dataContext.Table <Channel>().QueryRecordWhere("MeasurementTypeID = {0} AND MeasurementCharacteristicID = {1} AND PhaseID = {2} AND HarmonicGroup = {3} AND MeterID = {4}", pqMeasurement.MeasurementTypeID, pqMeasurement.MeasurementCharacteristicID, pqMeasurement.PhaseID, pqMeasurement.HarmonicGroup, meter.ID);
                    StepChangeStat record        = dataContext.Table <StepChangeStat>().QueryRecordWhere("MeterID = {0} AND Date = {1} AND StepChangeMeasurementID = {2}", meter.ID, startTime, measurement.ID);
                    Unit           unit          = dataContext.Table <Unit>().QueryRecordWhere("ID = {0}", pqMeasurement.UnitID);

                    if (record == null)
                    {
                        record         = new StepChangeStat();
                        record.MeterID = meter.ID;
                        record.StepchangeMeasurementID = measurement.ID;
                        record.Date = startTime;
                    }

                    record.Value = 0;

                    if (channel != null)
                    {
                        IEnumerable <openHistorian.XDALink.TrendingDataPoint> data = historian.Read(new[] { channel.ID }, startTime.AddHours(-1), endTime).Where(x => x.SeriesID == SeriesID.Average).ToList();

                        // no associated data for this measurement;  just return without creating the record.
                        if (!data.Any())
                        {
                            return;
                        }

                        try
                        {
                            foreach (openHistorian.XDALink.TrendingDataPoint point in data)
                            {
                                if (point.Timestamp >= startTime)
                                {
                                    double lastHourAvg = data.Where(x => x.Timestamp >= point.Timestamp.AddHours(-1) && x.Timestamp < point.Timestamp).Select(x => x.Value).Average();

                                    double std     = data.StandardDeviation(x => x.Value);
                                    double average = data.Average(x => x.Value);

                                    // if value is outside 5 sigma, do not check for step change
                                    if (point.Value > average + std * 5 || point.Value < average - std * 5)
                                    {
                                        continue;
                                    }

                                    if (unit.Name == "Percent")
                                    {
                                        if (Math.Abs(point.Value - lastHourAvg) > measurement.Setting)
                                        {
                                            record.Value++;
                                        }
                                    }
                                    else
                                    {
                                        if ((Math.Abs(point.Value - lastHourAvg) * 100 / lastHourAvg) > measurement.Setting)
                                        {
                                            record.Value++;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // no associated data for this measurement;  just return without creating the record.
                            return;
                        }
                    }

                    if (record.Value > 0)
                    {
                        dataContext.Table <StepChangeStat>().AddNewOrUpdateRecord(record);
                    }
                }
        }
示例#57
0
 public void Long(IEnumerable <long> source, double expected)
 {
     Assert.Equal(expected, source.Average());
     Assert.Equal(expected, source.Average(x => x));
 }
 public static double Average(this IEnumerable <Datum> @this)
 {
     return(@this.Average(datum => datum.Value));
 }
 private double CalculateStdDev(IEnumerable<double> values)
 {
     double ret = 0;
     if (values.Count() > 0)
     {
         double avg = values.Average();
         double sum = values.Sum(d => Math.Pow(d - avg, 2));
         ret = Math.Sqrt((sum) / (values.Count() - 1));
     }
     return ret;
 }
示例#60
0
 public void Average_Double(IEnumerable <double> source, double expected)
 {
     Assert.Equal(expected, source.Average());
     Assert.Equal(expected, source.Average(x => x));
 }