private void btn_simulate_Click(object sender, RoutedEventArgs e) { int nbrSim = Convert.ToInt32(txt_nbrsim.Text); double initWealth = Properties.Settings.Default.InitWealth; List<double> finalEarnings = new List<double>(); List<int> counts = new List<int>(); for (int i = 0; i < nbrSim; i++) { MartStrategy MStrat = new MartStrategy(5, 250, initWealth); double bid = MStrat.Bet(); Number res; double payoff; int count = 0; while (bid <= MStrat.Wealth) { MStrat.PlaceBet(bid); res = _RGame.Play(); payoff = _RGame.GetPayoffColor(NumberColor.Red, bid, res); MStrat.Setup(payoff); bid = MStrat.Bet(); count++; } finalEarnings.Add(MStrat.Earnings-initWealth); counts.Add(count); } txt_earnings.Text = finalEarnings.Average().ToString(); txt_plays.Text = counts.Average().ToString(); txt_maxEarnings.Text = finalEarnings.Max().ToString(); txt_maxLosses.Text = finalEarnings.Min().ToString(); txt_totEarnings.Text = finalEarnings.Where(x => x > 0).Sum().ToString(); txt_totLosses.Text = finalEarnings.Where(x => x < 0).Sum().ToString(); txt_balance.Text = finalEarnings.Sum().ToString(); }
//At the end of a trajectory, this updates the row with final info public void updateTrajectory() { try { TrajectoryDbDataSet.trajectoriesRow currentRow = Globals.ds.trajectories.FindByt_id(this.t_id); //update row with final values //currentRow.end_time = DateTime.Now; //Average velocity and direction double velocitySum = 0; int directionSumH = 0; int directionSumV = 0; int rows = 0; List<double> velocities = new List<double>(); List<double> velocities_filtered = new List<double>(); TrajectoryDbDataSet.pointsRow[] pointrows = Globals.ds.points.Select(String.Format("t_id = {0}", t_id)) as TrajectoryDbDataSet.pointsRow[]; foreach (TrajectoryDbDataSet.pointsRow row in pointrows) { velocities.Add((double)row[5]); directionSumH += Direction.Contains("E") ? 1 : 0; directionSumV += Direction.Contains("N") ? 1 : 0; velocities_filtered.Add(Math.Sqrt(row.vx * row.vx + row.vz * row.vz)); rows++; if (rows == pointrows.Count()) { currentRow.end_time = currentRow.start_time.AddMilliseconds(row.milliseconds); } } ///<summary> ///Filtering out outliers. Find the standard deviation of all velocity values. If values lie outside of two standard ///deviations they are ignored from the average velocity calculation. double mean = velocities.Average(); double stdev = StandardDeviation(velocities); int n = 0; foreach (double v in velocities) { if (v > (mean - 2* stdev) && v < (mean + 2*stdev)) { velocitySum += v; n++; } } double tester = velocitySum/n; currentRow.average_velocity = (tester.CompareTo(double.NaN)>0) ? tester: mean; currentRow.average_direction = ((directionSumV / rows > 0.5) ? "N" : "S") + ((directionSumH / rows > 0.5) ? "E" : "W"); currentRow.length = this.Distance; currentRow.speed_kalmanized = velocities_filtered.Average(); } catch (Exception e) { return; } }
/// <summary> /// CreateRandomList /// </summary> /// <returns></returns> private List<Value> CreateRandomValueList() { List<Value> List = new List<Value>(); for (int i = 0; i < LIST_SIZE; i++) List.Add(new Value(i, RandomDouble(0,10,3))); if (TheResult == null) TheResult = new Result(); TheResult.ResultValue = List.Average<Value>(x => x.DValue); return List; }
private void Button_Click(object sender, RoutedEventArgs e) { //LUCAS try { Random rand = new Random(42); List<int> numbers = new List<int>(); ListDisjointSet<int> disjointSet; disjointSet = new ListDisjointSet<int>(); Stopwatch iterationTimer = new Stopwatch(); List<long> ticksList = new List<long>(); for (int i = 0; i < 10000; i++) { int n = rand.Next(); numbers.Add(n); iterationTimer.Start(); disjointSet.MakeSet(n); iterationTimer.Stop(); ticksList.Add(iterationTimer.ElapsedTicks); iterationTimer.Reset(); } mksetOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min()); ticksList.Clear(); for (int i = 0; i < numbers.Count * 3; i++) { int lookup = numbers[rand.Next(numbers.Count)]; iterationTimer.Start(); disjointSet.Find(lookup); iterationTimer.Stop(); ticksList.Add(iterationTimer.ElapsedTicks); iterationTimer.Reset(); } findOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min()); ticksList.Clear(); for (int i = 0; i < numbers.Count * 3; i++) { int lookupA = numbers[rand.Next(numbers.Count)]; int lookupB = numbers[rand.Next(numbers.Count)]; iterationTimer.Start(); disjointSet.Union(disjointSet.Find(lookupA), disjointSet.Find(lookupB)); iterationTimer.Stop(); ticksList.Add(iterationTimer.ElapsedTicks); iterationTimer.Reset(); } unionOne.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min()); } catch (Exception err) { Console.WriteLine(err.StackTrace); } //PAUL try { Random rand = new Random(42); List<int> numbers = new List<int>(); DisjointDataSet<int> disjointSet; disjointSet = new DisjointDataSet<int>(); Stopwatch iterationTimer = new Stopwatch(); List<long> ticksList = new List<long>(); for (int i = 0; i < 10000; i++) { int n = rand.Next(); numbers.Add(n); iterationTimer.Start(); disjointSet.MakeSet(n); iterationTimer.Stop(); ticksList.Add(iterationTimer.ElapsedTicks); iterationTimer.Reset(); } mksetTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min()); ticksList.Clear(); for (int i = 0; i < numbers.Count * 3; i++) { int lookup = numbers[rand.Next(numbers.Count)]; iterationTimer.Start(); disjointSet.Find(lookup); iterationTimer.Stop(); ticksList.Add(iterationTimer.ElapsedTicks); iterationTimer.Reset(); } findTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min()); ticksList.Clear(); for (int i = 0; i < numbers.Count * 3; i++) { int lookupA = numbers[rand.Next(numbers.Count)]; int lookupB = numbers[rand.Next(numbers.Count)]; iterationTimer.Start(); disjointSet.Union(lookupA, lookupB); iterationTimer.Stop(); ticksList.Add(iterationTimer.ElapsedTicks); iterationTimer.Reset(); } unionTwo.Text = String.Format("Avg : {0}, Max: {1}, Min: {2}", ticksList.Average(), ticksList.Max(), ticksList.Min()); } catch (Exception err) { Console.WriteLine(err.StackTrace); } }
private void buttonDepthErrorEvaluation_Click(object sender, RoutedEventArgs e) { //以下改造 MotionDataHandler handler; string path; if (openMotionData(out handler, out path)) { CvMat resultMat = null; List<double> errorVarList = new List<double>(); int length = handler.FrameCount; IEnumerable<CvMat> depthImages; Utility.LoadImages(handler.GetDepthImagePaths(), out depthImages); foreach (CvMat depthMat in depthImages) { double errorVar = DepthUndistortionLinearCalibrator.EvaluateUndistortion(ref resultMat, depthMat, _undistortion); errorVarList.Add(errorVar); viewDepthUndistionMat(resultMat, depthMat); } displayLabels(); viewDepthUndistionMat(this.UndistortionData.UndistortionDepthMat); if (errorVarList.Count > 0) { double errorVarAvg = errorVarList.Average(); System.Windows.MessageBox.Show(string.Format("誤差分散の平均: {0}", errorVarAvg)); } } }
private void buttonScalingScore_Click(object sender, RoutedEventArgs e) { int cols, rows; double horizLength, vertLength; if (!parseChessboardParameters(out cols, out rows, out horizLength, out vertLength)) { return; } // 以下改造 MotionDataHandler handler; string path; if (openMotionData(out handler, out path)) { CvMat displayMat1 = null; CvMat displayMat3 = null; CvMat displayMat4 = null; CvMat gray = null; int length = handler.FrameCount; if (length == 0) { return; } CvSize boardSize = new CvSize(cols, rows); CvSize imageSize = new CvSize(); List<Tuple<double, double>> pairs = new List<Tuple<double, double>>(); CvPoint2D32f[] lastCorners = null; IEnumerable<CvMat> colorImages, depthImages; Utility.LoadImages(handler.GetColorImagePaths(), out colorImages); Utility.LoadImages(handler.GetDepthImagePaths(), out depthImages); var images = colorImages.Zip(depthImages, (first, second) => Tuple.Create(first, second)); foreach (Tuple<CvMat, CvMat> imagePair in images) { CvMat imageMat = imagePair.Item1; CvMat depthMat = imagePair.Item2; if (displayMat4 == null) { displayMat4 = CvEx.InitCvMat(imageMat); } imageSize = new CvSize(imageMat.Cols, imageMat.Rows); CvPoint2D32f[] corners; int count; CvEx.InitCvMat(ref gray, imageMat, MatrixType.U8C1); imageMat.CvtColor(gray, ColorConversion.RgbToGray); if (gray.FindChessboardCorners(boardSize, out corners, out count, ChessboardFlag.AdaptiveThresh)) { CvEx.CloneCvMat(ref displayMat1, imageMat); CvTermCriteria criteria = new CvTermCriteria(50, 0.01); gray.FindCornerSubPix(corners, count, new CvSize(3, 3), new CvSize(-1, -1), criteria); CvPoint3D32f?[] cornerPoints = new CvPoint3D32f?[corners.Length]; for (int j = 0; j < corners.Length; j++) { CvPoint2D32f corner = corners[j]; double? value = CalcEx.BilateralFilterDepthMatSinglePixel(corner, depthMat, 100, 4, 9); if (value.HasValue) { cornerPoints[j] = new CvPoint3D32f(corner.X, corner.Y, value.Value); } } for (int x = 0; x < cols; x++) { for (int y = 0; y < rows; y++) { if (!cornerPoints[x + y * cols].HasValue) continue; CvPoint3D32f point1 = cornerPoints[x + y * cols].Value; CvPoint3D64f undistortPoint1 = this.UndistortionData.GetRealFromScreenPos(point1, imageSize); foreach (var offset in new[] { new { X = 1, Y = 0, D = horizLength }, new { X = 0, Y = 1, D = vertLength } }) { int dx = x + offset.X; int dy = y + offset.Y; if (dx >= cols || dy >= rows) continue; if (!cornerPoints[dx + dy * cols].HasValue) continue; CvPoint3D32f point2 = cornerPoints[dx + dy * cols].Value; CvPoint3D64f undistortPoint2 = this.UndistortionData.GetRealFromScreenPos(point2, imageSize); double distance = Math.Sqrt(CvEx.GetDistanceSq(undistortPoint1, undistortPoint2)); double scale = distance / offset.D; CvColor color = CalcEx.HSVtoRGB(Math.Max(0, Math.Min(300, scale * 600 - 450)), scale, 2 - scale); displayMat4.DrawLine((int)point1.X, (int)point1.Y, (int)point2.X, (int)point2.Y, new CvScalar(color.R, color.G, color.B), 1, LineType.AntiAlias); pairs.Add(new Tuple<double, double>(distance, offset.D)); } } } CvEx.DrawChessboardCornerFrame(displayMat1, boardSize, corners, new CvScalar(64, 128, 64)); displayMat1.DrawChessboardCorners(boardSize, corners, true); lastCorners = corners; putImage(displayMat1, PixelFormats.Rgb24); } else { CvEx.CloneCvMat(ref displayMat3, imageMat); putImage(displayMat3, PixelFormats.Rgb24); } } CvMat displayMat2 = CvEx.InitCvMat(displayMat1); displayMat1.Undistort2(displayMat2, this.UndistortionData.CameraStruct.CreateCvMat(), this.UndistortionData.DistortStruct.CreateCvMat(true)); if (lastCorners != null) { drawUndistortedCornerFrame(displayMat2, lastCorners, boardSize); } displayMat2.PutText(string.Format("Min: {0}", pairs.Min(x => x.Item1 / x.Item2)), new CvPoint(20, 20), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255)); displayMat2.PutText(string.Format("Max: {0}", pairs.Max(x => x.Item1 / x.Item2)), new CvPoint(20, 40), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255)); displayMat2.PutText(string.Format("Avg: {0}", pairs.Average(x => x.Item1 / x.Item2)), new CvPoint(20, 60), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255)); displayMat2.PutText(string.Format("Med: {0}", CalcEx.GetMedian(pairs.Select(x => x.Item1 / x.Item2).ToList())), new CvPoint(20, 80), new CvFont(FontFace.HersheyPlain, 1, 1), new CvScalar(255, 255, 255)); putImage(displayMat4, PixelFormats.Rgb24); displayLabels(); } }
/// <summary>On avearage, do these two joints fall along nearby XYZ coordinates?</summary> /// <param name="j1">List of joints representing one joint's recent history</param> /// <param name="j2">List of joints representing one joint's recent history</param> /// <param name="Threshhold">Maximum standard deviation</param> /// <returns>True for close; false for far or excessive out of bounds</returns> public static bool arePointsCloseXYZ(List<Joint> j1, List<Joint> j2, double Threshhold = 0.2) { if (!arePointsCloseXYZ(j1, Threshhold)) return false; if (!arePointsCloseXYZ(j2, Threshhold)) return false; if (j1.Average(j => j.Position.X) - j2.Average(j => j.Position.X) > Threshhold) return false; if (j2.Average(j => j.Position.X) - j1.Average(j => j.Position.X) > Threshhold) return false; if (j1.Average(j => j.Position.Y) - j2.Average(j => j.Position.Y) > Threshhold) return false; if (j2.Average(j => j.Position.Y) - j1.Average(j => j.Position.Y) > Threshhold) return false; if (j1.Average(j => j.Position.Z) - j2.Average(j => j.Position.Z) > Threshhold) return false; if (j2.Average(j => j.Position.Z) - j1.Average(j => j.Position.Z) > Threshhold) return false; return true; }
private static void MoveStep_1(IList<Dot> dots, double percent) { // Find shortest pair lengths Tuple<int, int, double, Vector3D> absShortest = null; var subShortest = new List<Tuple<int, int, double, Vector3D>>(); for (int outer = 0; outer < dots.Count - 1; outer++) { Tuple<int, int, double, Vector3D> currentShortest = null; for (int inner = outer + 1; inner < dots.Count; inner++) { if (dots[outer].IsStatic && dots[inner].IsStatic) { continue; } Vector3D link = dots[inner].Position - dots[outer].Position; double lenSqr = (link).LengthSquared; if (currentShortest == null || lenSqr < currentShortest.Item3) { currentShortest = Tuple.Create(outer, inner, lenSqr, link); } } if (currentShortest == null) { continue; } currentShortest = Tuple.Create(currentShortest.Item1, currentShortest.Item2, Math.Sqrt(currentShortest.Item3), currentShortest.Item4); subShortest.Add(currentShortest); if (absShortest == null || currentShortest.Item3 < absShortest.Item3) { absShortest = currentShortest; } } if (subShortest.Count == 0) { return; } // Move the shortest pair away from each other (based on how far they are away from the avg) double avg = subShortest.Average(o => o.Item3); double distToMove = avg - absShortest.Item3; // the shortest will always be less than average Vector3D displace = absShortest.Item4.ToUnit() * (distToMove * percent); if (!dots[absShortest.Item1].IsStatic) dots[absShortest.Item1].Position -= displace; if (!dots[absShortest.Item2].IsStatic) dots[absShortest.Item2].Position += displace; }
private static double CalculateFrameRate(TimeSpan currentTimeStamp, ref TimeSpan lastTimeStamp, ref List<double> oldIntervals) { double newInterval = currentTimeStamp.TotalMilliseconds - lastTimeStamp.TotalMilliseconds; lastTimeStamp = currentTimeStamp; if (oldIntervals.Count >= 20) //Computes a running average of 20 frames for stability { oldIntervals.RemoveAt(0); } oldIntervals.Add(newInterval); return (1.0 / oldIntervals.Average() * 1000.0); }