Beispiel #1
0
        public void SaveFile(string videoFileName, IMouseDataResult data)
        {
            string fileLocation = FileBrowser.SaveFile("ART|*.art");

            if (string.IsNullOrWhiteSpace(fileLocation))
            {
                return;
            }

            SaveFile(fileLocation, videoFileName, data);
        }
Beispiel #2
0
        public ReviewWindowViewModel(ISingleMouse model, Dictionary <ISingleFile, IMouseDataResult> results, string artFile)
        {
            ObservableCollection <SingleFileViewModel> videos = new ObservableCollection <SingleFileViewModel>();

            foreach (ISingleFile singleFile in model.VideoFiles)
            {
                SingleFileViewModel vm   = new SingleFileViewModel(singleFile, artFile);
                IMouseDataResult    data = results[singleFile];

                if (data != null)
                {
                    vm.VideoOutcome = data.VideoOutcome;

                    if (data.VideoOutcome != SingleFileResult.Ok)
                    {
                        vm.Comments = data.Message;
                    }
                    else
                    {
                        vm.Comments = data.MainBehaviour;
                    }
                }
                videos.Add(vm);
            }

            SingleFiles         = videos;
            Model               = model;
            Results             = results;
            ArtFile             = artFile;
            GapDistanceMin      = 5;
            GapDistanceMax      = 300;
            BinaryThresholdMin  = 0;
            BinaryThresholdMax  = 255;
            BinaryThreshold2Min = 0;
            BinaryThreshold2Max = 255;

            Name = Model.Name;
            Age  = Model.Age;
            Type = Model.Type;

            SelectedVideo = SingleFiles.First();
        }
Beispiel #3
0
        private void ReRunVideo(string fileName)
        {
            ProgressView      view      = new ProgressView();
            ProgressViewModel viewModel = new ProgressViewModel();

            view.DataContext         = viewModel;
            viewModel.CancelPressed += (sender, args) =>
            {
                CancelReRun();
            };

            viewModel.WindowAboutToClose += (sender, args) =>
            {
                if (RbskVideo != null)
                {
                    RbskVideo.Paused = true;
                }
            };

            viewModel.WindowClosingCancelled += (sender, args) =>
            {
                if (RbskVideo != null)
                {
                    RbskVideo.Paused = false;
                }
            };

            CancelTask = false;

            Task.Factory.StartNew(() =>
            {
                IMouseDataResult result = Model.Results[SelectedVideo.Model];
                try
                {
                    IVideoSettings videoSettings = ModelResolver.Resolve <IVideoSettings>();
                    using (IRBSKVideo rbskVideo = ModelResolver.Resolve <IRBSKVideo>())
                        using (IVideo video = ModelResolver.Resolve <IVideo>())
                        {
                            RbskVideo = rbskVideo;
                            video.SetVideo(fileName);
                            if (video.FrameCount < 100)
                            {
                                result.VideoOutcome = SingleFileResult.FrameCountTooLow;
                                result.Message      = "Exception: " + SelectedVideo.VideoFileName + " - Frame count too low";
                                //allResults.TryAdd(file, result);
                                viewModel.ProgressValue = 1;
                                //continue;
                                return;
                            }

                            videoSettings.FileName       = SelectedVideo.VideoFileName;
                            videoSettings.ThresholdValue = BinaryThreshold;


                            video.SetFrame(0);
                            Image <Gray, Byte> binaryBackground;
                            IEnumerable <IBoundaryBase> boundaries;
                            videoSettings.GeneratePreview(video, out binaryBackground, out boundaries);
                            result.Boundaries = boundaries.ToArray();

                            rbskVideo.GapDistance    = GapDistance;
                            rbskVideo.ThresholdValue = BinaryThreshold;

                            rbskVideo.Video           = video;
                            rbskVideo.BackgroundImage = binaryBackground;

                            rbskVideo.ProgressUpdates += (s, e) =>
                            {
                                double progress = e.Progress;
                                if (progress >= 1)
                                {
                                    progress = 0.999;
                                }
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    viewModel.ProgressValue = progress;
                                });
                            };

                            rbskVideo.Process();
                            RbskVideo = null;
                            //if (Stop)
                            //{
                            //    state.Stop();
                            //    return;
                            //}
                            if (CancelTask)
                            {
                                return;
                            }
                            result.Results = rbskVideo.HeadPoints;
                            result.GenerateResults();
                            result.VideoOutcome = SingleFileResult.Ok;
                            //allResults.TryAdd(SelectedVideo, result);
                        }

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        result.ResetFrames();
                        Results[SelectedVideo.Model] = result;
                        CurrentResult = result;
                        SliderValueChanged();
                        SaveCommand.RaiseCanExecuteChangedNotification();
                        viewModel.ProgressValue = 1;
                        SelectedVideoChanged();
                    });
                }
                catch (Exception e)
                {
                    result.VideoOutcome = SingleFileResult.Error;
                    result.Message      = "Exception: " + SelectedVideo.VideoFileName + " - " + e.Message;
                    //allResults.TryAdd(SelectedVideo, result);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        viewModel.ProgressValue = 1;
                    });
                    RbskVideo = null;
                }
            });

            view.ShowDialog();
        }
Beispiel #4
0
 public void SaveFile(string fileLocation, string videoFileName, IMouseDataResult data)
 {
     SaveFile(fileLocation, videoFileName, data.VideoOutcome, data.Results, data.MotionTrack, data.SmoothedMotionTrack, data.OrientationTrack, data.Events, data.Boundaries, data.InteractingBoundries, data.MinInteractionDistance, data.GapDistance, data.ThresholdValue, data.ThresholdValue2, data.StartFrame, data.EndFrame, data.FrameRate, data.SmoothMotion, data.SmoothFactor, data.CentroidSize, data.PelvicArea, data.PelvicArea2, data.PelvicArea3, data.PelvicArea4, data.UnitsToMilimeters, data.ROI, data.Message);
 }
Beispiel #5
0
        //private void Closing(object args)
        //{
        //    if (!Running)
        //    {
        //        return;
        //    }

        //    var result = MessageBox.Show("The program is currently running, are you sure you want to cancel it?", "Batch Running", MessageBoxButton.YesNo, MessageBoxImage.Question);

        //    if (result == MessageBoxResult.Yes)
        //    {
        //        IEnumerable<SingleMouseViewModel> allMice = TgItemsSource.Concat(NtgItemsSource);
        //        foreach (SingleMouseViewModel mouse in allMice)
        //        {
        //            mouse.Stop = true;
        //        }
        //        Running = false;
        //        return;
        //    }

        //    CancelEventArgs cancelEventArgs = args as CancelEventArgs;
        //    if (cancelEventArgs != null)
        //    {
        //        cancelEventArgs.Cancel = true;
        //    }
        //}

        private void LoadOutputFolder()
        {
            IRepository repo            = RepositoryResolver.Resolve <IRepository>();
            string      initialLocation = repo.GetValue <string>("OutputFolderLocation");

            string folderLocation = FileBrowser.BrowseForFolder(initialLocation);

            if (string.IsNullOrWhiteSpace(folderLocation))
            {
                return;
            }

            repo.SetValue("OutputFolderLocation", folderLocation);
            repo.Save();

            string[] artFiles = Directory.GetFiles(folderLocation, "*.art");

            foreach (string file in artFiles)
            //Parallel.ForEach(artFiles, file =>
            {
                string videoFileName = Path.GetFileNameWithoutExtension(file);

                //if (videoFileName.Contains("091119-0038"))
                //{
                //    Console.WriteLine("h");
                //}

                if (string.IsNullOrWhiteSpace(videoFileName))
                {
                    continue;
                    //return;
                }

                //if (videoFileName.Contains("091218-0179"))
                //{
                //    Console.WriteLine("test");
                //}

                //SingleMouseViewModel mouse = null;
                ////videoFileName = file.Replace(".art", "");
                //bool testBreak = false;
                //foreach (var listMouse in TgItemsSource)
                //{
                //    foreach (var temp in listMouse.VideoFiles)
                //    {
                //        if (temp.VideoFileName.Contains(videoFileName))
                //        {
                //            mouse = listMouse;
                //            testBreak = true;
                //            break;
                //        }
                //    }

                //    if (testBreak)
                //    {
                //        break;
                //    }
                //}

                SingleMouseViewModel mouse = TgItemsSource.FirstOrDefault(x => x.VideoFiles.FirstOrDefault(y => y.VideoFileName.Contains(videoFileName)) != null);

                if (mouse == null)
                {
                    //Can't find mouse
                    //return;
                    continue;
                }

                ISingleFile singleFile = mouse.VideoFiles.First(x => x.VideoFileName.Contains(videoFileName));

                XmlSerializer   serializer = new XmlSerializer(typeof(TrackedVideoXml));
                TrackedVideoXml trackedVideoXml;
                using (StreamReader reader = new StreamReader(file))
                {
                    trackedVideoXml = (TrackedVideoXml)serializer.Deserialize(reader);
                }

                ITrackedVideo trackedVideo = trackedVideoXml.GetData();

                IMouseDataResult mouseDataResult = ModelResolver.Resolve <IMouseDataResult>();

                if (trackedVideo.Result != SingleFileResult.Ok)
                {
                    mouseDataResult.Message      = trackedVideo.Message;
                    mouseDataResult.VideoOutcome = trackedVideo.Result;

                    if (mouse.Results == null)
                    {
                        mouse.Results = new Dictionary <ISingleFile, IMouseDataResult>();
                    }
                    mouse.Results.Add(singleFile, mouseDataResult);
                    mouse.ReviewCommand.RaiseCanExecuteChangedNotification();
                    mouse.UpdateProgress(singleFile, 1);

                    continue;
                }

                var tempResults = trackedVideo.Results;
                Dictionary <int, ISingleFrameResult> results = new Dictionary <int, ISingleFrameResult>();
                foreach (var kvp in tempResults)
                {
                    ISingleFrameResult singleFrame = ModelResolver.Resolve <ISingleFrameResult>();

                    if (kvp.Value != null)
                    {
                        ISingleFrameResult tempResult = kvp.Value;
                        singleFrame.HeadPoints        = tempResult.HeadPoints;
                        singleFrame.CentroidSize      = tempResult.CentroidSize;
                        singleFrame.PelvicArea        = tempResult.PelvicArea;
                        singleFrame.PelvicArea2       = tempResult.PelvicArea2;
                        singleFrame.PelvicArea3       = tempResult.PelvicArea3;
                        singleFrame.PelvicArea4       = tempResult.PelvicArea4;
                        singleFrame.SmoothedHeadPoint = tempResult.SmoothedHeadPoint;
                        singleFrame.Centroid          = tempResult.Centroid;
                    }

                    results.Add(kvp.Key, singleFrame);
                }


                mouseDataResult.Name              = mouse.Id;
                mouseDataResult.Results           = results;
                mouseDataResult.Age               = mouse.Age;
                mouseDataResult.Boundaries        = trackedVideo.Boundries;
                mouseDataResult.VideoOutcome      = SingleFileResult.Ok;
                mouseDataResult.GapDistance       = trackedVideo.GapDistance;
                mouseDataResult.ThresholdValue    = trackedVideo.ThresholdValue;
                mouseDataResult.ThresholdValue2   = trackedVideo.ThresholdValue2;
                mouseDataResult.StartFrame        = trackedVideo.StartFrame;
                mouseDataResult.EndFrame          = trackedVideo.EndFrame;
                mouseDataResult.SmoothMotion      = trackedVideo.SmoothMotion;
                mouseDataResult.FrameRate         = trackedVideo.FrameRate;
                mouseDataResult.UnitsToMilimeters = trackedVideo.UnitsToMilimeters;
                mouseDataResult.SmoothFactor      = 0.68;
                mouseDataResult.GenerateResults(file);
                mouseDataResult.PelvicArea  = trackedVideo.PelvicArea1;
                mouseDataResult.PelvicArea2 = trackedVideo.PelvicArea2;
                mouseDataResult.PelvicArea3 = trackedVideo.PelvicArea3;
                mouseDataResult.PelvicArea4 = trackedVideo.PelvicArea4;
                mouseDataResult.Type        = mouse.Type;
                mouseDataResult.DataLoadComplete();

                if (mouse.Results == null)
                {
                    mouse.Results = new Dictionary <ISingleFile, IMouseDataResult>();
                }

                mouse.UpdateProgress(singleFile, 1);
                mouse.Results.Add(singleFile, mouseDataResult);
                mouse.ReviewCommand.RaiseCanExecuteChangedNotification();
            }//);

            ExportAllCommand.RaiseCanExecuteChangedNotification();
        }
        private void GenerateIndivResultsFinal()
        {
            int rows    = 1000;
            int columns = 22;

            object[,] data = new object[rows, columns];

            int rowCounter = 1;

            data[0, 0]  = "Mouse";
            data[0, 1]  = "Type";
            data[0, 2]  = "Age";
            data[0, 3]  = "Clip";
            data[0, 4]  = "Centroid Width";
            data[0, 5]  = "Distance";
            data[0, 6]  = "Max Velocity";
            data[0, 7]  = "Max Angular Velocity";
            data[0, 8]  = "Average Velocity";
            data[0, 9]  = "Average Angular Velocity";
            data[0, 10] = "Average Pelvic Area 1";
            data[0, 11] = "Average Pelvic Area 2";
            data[0, 12] = "Average Pelvic Area 3";
            data[0, 13] = "Average Pelvic Area 4";
            data[0, 14] = "Average Centroid Velocity";
            data[0, 15] = "Max Centroid Velocity";
            data[0, 16] = "Clip Duration";
            data[0, 17] = "Percentage Running";
            data[0, 18] = "Percentage moving";
            data[0, 19] = "Percentage turning";
            data[0, 20] = "Percentage Still";
            data[0, 21] = "Percentage Interacting";

            Dictionary <BatchProcessViewModel.BrettTuple <string, int>, IMouseDataResult> sortedResults  = new Dictionary <BatchProcessViewModel.BrettTuple <string, int>, IMouseDataResult>();
            Dictionary <BatchProcessViewModel.BrettTuple <string, int>, CounterClass>     sortedCounters = new Dictionary <BatchProcessViewModel.BrettTuple <string, int>, CounterClass>();
            List <MouseHolder> mice = new List <MouseHolder>();

            foreach (SingleMouseViewModel mouse in Videos)
            {
                mice.AddRange(from video in mouse.VideoFiles let result = mouse.Results[video] select new MouseHolder()
                {
                    Age = mouse.Age.ToString(), Class = mouse.Class, File = video.VideoFileName, Mouse = mouse, Result = result, Type = mouse.Type.Name
                });
            }
            try
            {
                foreach (MouseHolder mouse in mice)
                {
                    BatchProcessViewModel.BrettTuple <string, int> key = new BatchProcessViewModel.BrettTuple <string, int>(mouse.Mouse.Id, mouse.Mouse.Age);

                    IMouseDataResult finalResult;
                    CounterClass     counter;
                    if (sortedResults.ContainsKey(key))
                    {
                        finalResult = sortedResults[key];
                        counter     = sortedCounters[key];
                    }
                    else
                    {
                        finalResult      = ModelResolver.Resolve <IMouseDataResult>();
                        finalResult.Name = mouse.Mouse.Id;
                        finalResult.Age  = mouse.Mouse.Age;
                        finalResult.Type = mouse.Mouse.Type;

                        counter = new CounterClass();
                        sortedResults.Add(key, finalResult);
                        sortedCounters.Add(key, counter);
                    }

                    IMouseDataResult result = mouse.Result;

                    if (result.EndFrame - result.StartFrame < 100)
                    {
                        continue;
                    }

                    double centroidWidth       = result.GetCentroidWidthForRunning();
                    double distanceTravelled   = result.DistanceTravelled;
                    double maxSpeed            = result.MaxSpeed;
                    double maxAngVelocity      = result.MaxAngularVelocty;
                    double avgVelocity         = result.GetAverageSpeedForMoving();
                    double averageAngVelocity  = result.AverageAngularVelocity;
                    double avgPelvic1          = result.GetCentroidWidthForPelvic1();
                    double avgPelvic2          = result.GetCentroidWidthForPelvic2();
                    double avgPelvic3          = result.GetCentroidWidthForPelvic3();
                    double avgPelvic4          = result.GetCentroidWidthForPelvic4();
                    double avgCentroidVelocity = result.GetAverageCentroidSpeedForMoving();
                    double maxCentroidVelocity = result.MaxCentroidSpeed;
                    double duration            = result.EndFrame - result.StartFrame;

                    avgVelocity         /= 1000;
                    avgCentroidVelocity /= 1000;
                    maxSpeed            /= 1000;
                    maxCentroidVelocity /= 1000;
                    averageAngVelocity  /= 1000;
                    maxAngVelocity      /= 1000;

                    int frameDelta = result.EndFrame - result.StartFrame;
                    List <Tuple <int, int> > movingFrameNumbers      = result.GetFrameNumbersForMoving();
                    List <Tuple <int, int> > runningFrameNumbers     = result.GetFrameNumbersForRunning();
                    List <Tuple <int, int> > turningFrameNumbers     = result.GetFrameNumbersForTurning();
                    List <Tuple <int, int> > stillFrameNumbers       = result.GetFrameNumbersForStill();
                    List <Tuple <int, int> > interactingFrameNumbers = result.GetFrameNumbesrForInteracting();

                    int movingFrameCount = 0, runningFrameCount = 0, turningFrameCount = 0, stillFrameCount = 0;

                    if (movingFrameNumbers != null && movingFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in movingFrameNumbers)
                        {
                            int delta = t.Item2 - t.Item1;
                            movingFrameCount += delta;
                        }
                    }

                    if (runningFrameNumbers != null && runningFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in runningFrameNumbers)
                        {
                            int delta = t.Item2 - t.Item1;
                            runningFrameCount += delta;
                        }
                    }

                    if (stillFrameNumbers != null && stillFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in stillFrameNumbers)
                        {
                            int delta = t.Item2 - t.Item1;
                            stillFrameCount += delta;
                        }
                    }

                    if (turningFrameNumbers != null && turningFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in turningFrameNumbers)
                        {
                            int delta = t.Item2 - t.Item1;
                            turningFrameCount += delta;
                        }
                    }

                    List <int> allInteractingFrameNumbers = new List <int>();
                    if (interactingFrameNumbers != null && interactingFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in interactingFrameNumbers)
                        {
                            int start = t.Item1;
                            int end   = t.Item2;

                            for (int i = start; i <= end; i++)
                            {
                                if (!allInteractingFrameNumbers.Contains(i))
                                {
                                    allInteractingFrameNumbers.Add(i);
                                }
                            }
                        }
                    }

                    double movingPercentage  = (double)movingFrameCount / frameDelta;
                    double runningPercentage = (double)runningFrameCount / frameDelta;
                    double turningPercentage = (double)turningFrameCount / frameDelta;
                    double stillPercentage   = (double)stillFrameCount / frameDelta;

                    int fCount = allInteractingFrameNumbers.Count - 1;
                    if (fCount < 0)
                    {
                        fCount = 0;
                    }
                    double interactionPercentage = (double)fCount / frameDelta;

                    if (centroidWidth > 0)
                    {
                        finalResult.CentroidSize += centroidWidth;
                        counter.CentroidWidth++;
                    }

                    if (distanceTravelled > 0)
                    {
                        finalResult.DistanceTravelled += distanceTravelled;
                        counter.Distance++;
                    }

                    if (maxSpeed > 0)
                    {
                        if (maxSpeed > finalResult.MaxSpeed)
                        {
                            finalResult.MaxSpeed = maxSpeed;
                        }

                        //counter.MaxVelocity++;
                    }

                    if (maxAngVelocity > 0)
                    {
                        if (maxAngVelocity > finalResult.MaxAngularVelocty)
                        {
                            finalResult.MaxAngularVelocty = maxAngVelocity;
                        }

                        //counter.MaxAngVelocity++;
                    }

                    if (avgVelocity > 0)
                    {
                        finalResult.AverageVelocity += avgVelocity;
                        counter.AvgVelocity++;
                    }

                    if (averageAngVelocity > 0)
                    {
                        finalResult.AverageAngularVelocity += averageAngVelocity;
                        counter.AvgAngVelocity++;
                    }

                    if (avgPelvic1 > 0)
                    {
                        finalResult.PelvicArea += avgPelvic1;
                        counter.AvgPelvic1++;
                    }

                    if (avgPelvic2 > 0)
                    {
                        finalResult.PelvicArea2 += avgPelvic2;
                        counter.AvgPelvic2++;
                    }

                    if (avgPelvic3 > 0)
                    {
                        finalResult.PelvicArea3 += avgPelvic3;
                        counter.AvgPelvic3++;
                    }

                    if (avgPelvic4 > 0)
                    {
                        finalResult.PelvicArea4 += avgPelvic4;
                        counter.AvgPelvic4++;
                    }

                    if (avgCentroidVelocity > 0)
                    {
                        finalResult.AverageCentroidVelocity += avgCentroidVelocity;
                        counter.AvgCentroidVelocity++;
                    }

                    if (maxCentroidVelocity > 0)
                    {
                        if (maxCentroidVelocity > finalResult.MaxCentroidSpeed)
                        {
                            finalResult.MaxCentroidSpeed += maxCentroidVelocity;
                        }

                        //counter.MaxCentroidVelocity++;
                    }

                    //if (duration > 0)
                    //{
                    finalResult.Duration += duration;
                    counter.ClipDuration++;
                    //}

                    //if (runningPercentage > 0)
                    //{
                    finalResult.Dummy += runningPercentage;
                    counter.PercentageRunning++;
                    //}

                    //if (movingPercentage > 0)
                    //{
                    finalResult.Dummy2 += movingPercentage;
                    counter.PercentageMoving++;
                    //}

                    //if (turningPercentage > 0)
                    //{
                    finalResult.Dummy3 += turningPercentage;
                    counter.PercentageTurning++;
                    //}

                    //if (stillPercentage > 0)
                    //{
                    finalResult.Dummy4 += stillPercentage;
                    counter.PercentageStill++;
                    //}

                    finalResult.Dummy5 += interactionPercentage;
                    counter.PercentageInteracting++;

                    //rowCounter++;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }

            string fileLocation = FileBrowser.SaveFile("Excel CSV|*.csv");

            if (string.IsNullOrWhiteSpace(fileLocation))
            {
                return;
            }

            foreach (var kvp in sortedResults)
            {
                var key                 = kvp.Key;
                var counter             = sortedCounters[key];
                IMouseDataResult result = kvp.Value;

                data[rowCounter, 0] = result.Name;
                data[rowCounter, 1] = result.Type;
                data[rowCounter, 2] = result.Age;
                //data[rowCounter, 3] = "Clip";
                data[rowCounter, 4]  = result.CentroidSize / counter.CentroidWidth;
                data[rowCounter, 5]  = result.DistanceTravelled / counter.Distance;
                data[rowCounter, 6]  = result.MaxSpeed;
                data[rowCounter, 7]  = result.MaxAngularVelocty;
                data[rowCounter, 8]  = result.AverageVelocity / counter.AvgVelocity;
                data[rowCounter, 9]  = result.AverageAngularVelocity / counter.AvgAngVelocity;
                data[rowCounter, 10] = result.PelvicArea / counter.AvgPelvic1;
                data[rowCounter, 11] = result.PelvicArea2 / counter.AvgPelvic2;
                data[rowCounter, 12] = result.PelvicArea3 / counter.AvgPelvic3;
                data[rowCounter, 13] = result.PelvicArea4 / counter.AvgPelvic4;
                data[rowCounter, 14] = result.AverageCentroidVelocity / counter.AvgCentroidVelocity;
                data[rowCounter, 15] = result.MaxSpeed;
                data[rowCounter, 16] = result.Duration / counter.ClipDuration;
                data[rowCounter, 17] = result.Dummy / counter.PercentageRunning;
                data[rowCounter, 18] = result.Dummy2 / counter.PercentageMoving;
                data[rowCounter, 19] = result.Dummy3 / counter.PercentageTurning;
                data[rowCounter, 20] = result.Dummy4 / counter.PercentageStill;
                data[rowCounter, 21] = result.Dummy5 / counter.PercentageInteracting;
                rowCounter++;
            }
            int rowCount    = data.GetLength(0);
            int columnCount = data.GetLength(1);

            StringBuilder sb = new StringBuilder();

            for (int i = 1; i <= rowCount; i++)
            {
                StringBuilder sb2 = new StringBuilder();
                for (int j = 1; j <= columnCount; j++)
                {
                    object dat = data[i - 1, j - 1];
                    sb2.Append(dat);

                    if (j < columnCount)
                    {
                        sb2.Append(",");
                    }
                }

                sb.AppendLine(sb2.ToString());
            }

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileLocation))
            {
                file.WriteLine(sb.ToString());
            }
        }
        private void GenerateAllResults()
        {
            int rows    = 1000;
            int columns = 22;

            object[,] data = new object[rows, columns];

            int rowCounter = 1;

            data[0, 0]  = "Mouse";
            data[0, 1]  = "Type";
            data[0, 2]  = "Age";
            data[0, 3]  = "Clip";
            data[0, 4]  = "Centroid Width";
            data[0, 5]  = "Distance";
            data[0, 6]  = "Max Velocity";
            data[0, 7]  = "Max Angular Velocity";
            data[0, 8]  = "Average Velocity";
            data[0, 9]  = "Average Angular Velocity";
            data[0, 10] = "Average Pelvic Area 1";
            data[0, 11] = "Average Pelvic Area 2";
            data[0, 12] = "Average Pelvic Area 3";
            data[0, 13] = "Average Pelvic Area 4";
            data[0, 14] = "Average Centroid Velocity";
            data[0, 15] = "Max Centroid Velocity";
            data[0, 16] = "Clip Duration";
            data[0, 17] = "Percentage Running";
            data[0, 18] = "Percentage moving";
            data[0, 19] = "Percentage turning";
            data[0, 20] = "Percentage Still";
            data[0, 21] = "Percentage Interacting";


            List <MouseHolder> mice = new List <MouseHolder>();

            foreach (SingleMouseViewModel mouse in Videos)
            {
                mice.AddRange(from video in mouse.VideoFiles let result = mouse.Results[video] select new MouseHolder()
                {
                    Age = mouse.Age.ToString(), Class = mouse.Class, File = video.VideoFileName, Mouse = mouse, Result = result, Type = mouse.Type.Name
                });
            }
            try
            {
                foreach (MouseHolder mouse in mice)
                {
                    IMouseDataResult result = mouse.Result;

                    if (result.EndFrame - result.StartFrame < 100)
                    {
                        continue;
                    }

                    data[rowCounter, 0] = mouse.Mouse.Name + " - " + mouse.Mouse.Id;
                    data[rowCounter, 1] = mouse.Type;
                    data[rowCounter, 2] = mouse.Age;
                    data[rowCounter, 3] = mouse.File;

                    double centroidWidth       = result.GetCentroidWidthForRunning();
                    double distanceTravelled   = result.DistanceTravelled;
                    double maxSpeed            = result.MaxSpeed;
                    double maxAngVelocity      = result.MaxAngularVelocty;
                    double avgVelocity         = result.GetAverageSpeedForMoving();
                    double averageAngVelocity  = result.AverageAngularVelocity;
                    double avgPelvic1          = result.GetCentroidWidthForPelvic1();
                    double avgPelvic2          = result.GetCentroidWidthForPelvic2();
                    double avgPelvic3          = result.GetCentroidWidthForPelvic3();
                    double avgPelvic4          = result.GetCentroidWidthForPelvic4();
                    double avgCentroidVelocity = result.GetAverageCentroidSpeedForMoving();
                    double maxCentroidVelocity = result.MaxCentroidSpeed;
                    double duration            = result.EndFrame - result.StartFrame;

                    avgVelocity         /= 1000;
                    avgCentroidVelocity /= 1000;
                    maxSpeed            /= 1000;
                    maxCentroidVelocity /= 1000;
                    averageAngVelocity  /= 1000;
                    maxAngVelocity      /= 1000;

                    int frameDelta = result.EndFrame - result.StartFrame;
                    List <Tuple <int, int> > movingFrameNumbers      = result.GetFrameNumbersForMoving();
                    List <Tuple <int, int> > runningFrameNumbers     = result.GetFrameNumbersForRunning();
                    List <Tuple <int, int> > turningFrameNumbers     = result.GetFrameNumbersForTurning();
                    List <Tuple <int, int> > stillFrameNumbers       = result.GetFrameNumbersForStill();
                    List <Tuple <int, int> > interactingFrameNumbers = result.GetFrameNumbesrForInteracting();

                    int movingFrameCount = 0, runningFrameCount = 0, turningFrameCount = 0, stillFrameCount = 0;

                    if (movingFrameNumbers != null && movingFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in movingFrameNumbers)
                        {
                            int delta = t.Item2 - t.Item1;
                            movingFrameCount += delta;
                        }
                    }

                    if (runningFrameNumbers != null && runningFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in runningFrameNumbers)
                        {
                            int delta = t.Item2 - t.Item1;
                            runningFrameCount += delta;
                        }
                    }

                    if (stillFrameNumbers != null && stillFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in stillFrameNumbers)
                        {
                            int delta = t.Item2 - t.Item1;
                            stillFrameCount += delta;
                        }
                    }

                    if (turningFrameNumbers != null && turningFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in turningFrameNumbers)
                        {
                            int delta = t.Item2 - t.Item1;
                            turningFrameCount += delta;
                        }
                    }

                    List <int> allInteractingFrameNumbers = new List <int>();
                    if (interactingFrameNumbers != null && interactingFrameNumbers.Any())
                    {
                        foreach (Tuple <int, int> t in interactingFrameNumbers)
                        {
                            int start = t.Item1;
                            int end   = t.Item2;

                            for (int i = start; i <= end; i++)
                            {
                                if (!allInteractingFrameNumbers.Contains(i))
                                {
                                    allInteractingFrameNumbers.Add(i);
                                }
                            }
                        }
                    }

                    double movingPercentage  = (double)movingFrameCount / frameDelta;
                    double runningPercentage = (double)runningFrameCount / frameDelta;
                    double turningPercentage = (double)turningFrameCount / frameDelta;
                    double stillPercentage   = (double)stillFrameCount / frameDelta;

                    int fCount = allInteractingFrameNumbers.Count - 1;
                    if (fCount < 0)
                    {
                        fCount = 0;
                    }
                    double interactionPercentage = (double)fCount / frameDelta;

                    if (centroidWidth > 0)
                    {
                        data[rowCounter, 4] = centroidWidth;
                    }

                    if (distanceTravelled > 0)
                    {
                        data[rowCounter, 5] = distanceTravelled;
                    }

                    if (maxSpeed > 0)
                    {
                        data[rowCounter, 6] = maxSpeed;
                    }

                    if (maxAngVelocity > 0)
                    {
                        data[rowCounter, 7] = maxAngVelocity;
                    }

                    if (avgVelocity > 0)
                    {
                        data[rowCounter, 8] = avgVelocity;
                    }

                    if (averageAngVelocity > 0)
                    {
                        data[rowCounter, 9] = averageAngVelocity;
                    }

                    if (avgPelvic1 > 0)
                    {
                        data[rowCounter, 10] = avgPelvic1;
                    }

                    if (avgPelvic2 > 0)
                    {
                        data[rowCounter, 11] = avgPelvic2;
                    }

                    if (avgPelvic3 > 0)
                    {
                        data[rowCounter, 12] = avgPelvic3;
                    }

                    if (avgPelvic4 > 0)
                    {
                        data[rowCounter, 13] = avgPelvic4;
                    }

                    if (avgCentroidVelocity > 0)
                    {
                        data[rowCounter, 14] = avgCentroidVelocity;
                    }

                    if (maxCentroidVelocity > 0)
                    {
                        data[rowCounter, 15] = maxCentroidVelocity;
                    }

                    if (duration > 0)
                    {
                        data[rowCounter, 16] = duration;
                    }

                    //if (runningPercentage > 0)
                    //{
                    data[rowCounter, 17] = runningPercentage;
                    //}

                    //if (movingPercentage > 0)
                    //{
                    data[rowCounter, 18] = movingPercentage;
                    //}

                    //if (turningPercentage > 0)
                    //{
                    data[rowCounter, 19] = turningPercentage;
                    //}

                    //if (stillPercentage > 0)
                    //{
                    data[rowCounter, 20] = stillPercentage;
                    //}

                    //if (interactionPercentage > 0)
                    //{
                    data[rowCounter, 21] = interactionPercentage;
                    //}

                    rowCounter++;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }

            string fileLocation = FileBrowser.SaveFile("Excel|*.xlsx");

            if (string.IsNullOrWhiteSpace(fileLocation))
            {
                return;
            }

            ExcelService.WriteData(data, fileLocation);
        }
        public void RunFiles(string outputLocation)
        {
            if (!string.IsNullOrWhiteSpace(outputLocation))
            {
                if (!outputLocation.EndsWith("\\"))
                {
                    outputLocation += "\\";
                }
            }

            Rbsk = new ConcurrentBag <IRBSKVideo>();
            ConcurrentDictionary <ISingleFile, IMouseDataResult> allResults = new ConcurrentDictionary <ISingleFile, IMouseDataResult>();
            List <ISingleFile> files = VideoFiles;

            foreach (var file in files)
            {
                IMouseDataResult result = ModelResolver.Resolve <IMouseDataResult>();
                result.Name = file.VideoFileName;
                result.Type = Type;

                ISaveArtFile save = ModelResolver.Resolve <ISaveArtFile>();
                string       artFile;
                string       videoFile = file.VideoFileName;
                if (string.IsNullOrWhiteSpace(outputLocation))
                {
                    string extension = Path.GetExtension(videoFile);
                    artFile = videoFile.Replace(extension, ".art");
                }
                else
                {
                    string fileName = Path.GetFileNameWithoutExtension(videoFile);
                    fileName += ".art";
                    artFile   = outputLocation + fileName;
                }

                ArtFile = artFile;

                if (File.Exists(artFile))
                {
                    XmlSerializer   serializer = new XmlSerializer(typeof(TrackedVideoXml));
                    TrackedVideoXml trackedVideoXml;
                    using (StreamReader reader = new StreamReader(artFile))
                    {
                        trackedVideoXml = (TrackedVideoXml)serializer.Deserialize(reader);
                    }

                    ITrackedVideo trackedVideo = trackedVideoXml.GetData();

                    result.Boundaries        = trackedVideo.Boundries;
                    result.VideoOutcome      = trackedVideo.Result;
                    result.GapDistance       = trackedVideo.GapDistance;
                    result.ThresholdValue    = trackedVideo.ThresholdValue;
                    result.ThresholdValue2   = trackedVideo.ThresholdValue2;
                    result.StartFrame        = trackedVideo.StartFrame;
                    result.EndFrame          = trackedVideo.EndFrame;
                    result.SmoothMotion      = trackedVideo.SmoothMotion;
                    result.FrameRate         = trackedVideo.FrameRate;
                    result.UnitsToMilimeters = trackedVideo.UnitsToMilimeters;
                    result.SmoothFactor      = 0.68;
                    result.GenerateResults(artFile);
                    result.PelvicArea  = trackedVideo.PelvicArea1;
                    result.PelvicArea2 = trackedVideo.PelvicArea2;
                    result.PelvicArea3 = trackedVideo.PelvicArea3;
                    result.PelvicArea4 = trackedVideo.PelvicArea4;
                    result.Results     = trackedVideo.Results;
                    result.GenerateResults();
                    result.DataLoadComplete();

                    allResults.TryAdd(file, result);

                    UpdateProgress(file, 1);
                    continue;
                }

                try
                {
                    IVideoSettings videoSettings = ModelResolver.Resolve <IVideoSettings>();
                    using (IRBSKVideo rbskVideo = ModelResolver.Resolve <IRBSKVideo>())
                        using (IVideo video = ModelResolver.Resolve <IVideo>())
                        {
                            Rbsk.Add(rbskVideo);
                            video.SetVideo(file.VideoFileName);
                            if (video.FrameCount <= 100)
                            {
                                result.VideoOutcome = SingleFileResult.FrameCountTooLow;
                                result.Message      = "Exception: " + file.VideoFileName + " - Frame count too low";
                                allResults.TryAdd(file, result);
                                UpdateProgress(file, 1);
                                save.SaveFile(artFile, videoFile, result);
                                continue;
                            }

                            result.FrameRate = video.FrameRate;
                            video.SetFrame(0);

                            videoSettings.FileName       = file.VideoFileName;
                            videoSettings.ThresholdValue = ThresholdValue;

                            Image <Gray, Byte>          binaryBackground;
                            IEnumerable <IBoundaryBase> boundaries;
                            videoSettings.GeneratePreview(video, out binaryBackground, out boundaries);
                            result.Boundaries = boundaries.ToArray();

                            rbskVideo.Video           = video;
                            rbskVideo.GapDistance     = GapDistance;
                            rbskVideo.BackgroundImage = binaryBackground;
                            rbskVideo.ThresholdValue  = ThresholdValue;
                            rbskVideo.ThresholdValue2 = ThresholdValue2;

                            rbskVideo.ProgressUpdates += (s, e) => UpdateProgress(file, e.Progress);
                            rbskVideo.Process();

                            if (Stop)
                            {
                                return;
                            }

                            result.GapDistance            = rbskVideo.GapDistance;
                            result.MinInteractionDistance = 15;
                            result.ThresholdValue         = rbskVideo.ThresholdValue;
                            result.ThresholdValue2        = rbskVideo.ThresholdValue2;

                            result.Results = rbskVideo.HeadPoints;
                            result.ResetFrames();
                            //result.FrameRate = FrameRate;
                            result.SmoothMotion = SmoothMotion;
                            result.GenerateResults();
                            result.VideoOutcome = SingleFileResult.Ok;
                            result.DataLoadComplete();
                            allResults.TryAdd(file, result);

                            save.SaveFile(artFile, videoFile, result);
                        }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    Console.WriteLine(e.Message);
                    result.VideoOutcome = SingleFileResult.Error;
                    result.Message      = "Exception: " + file.VideoFileName + " - " + e.Message + " - " + e.StackTrace;
                    result.DataLoadComplete();
                    allResults.TryAdd(file, result);
                    UpdateProgress(file, 1);
                    save.SaveFile(artFile, videoFile, result);
                }

                if (Cancel)
                {
                    break;
                }

                if (Stop)
                {
                    return;
                }
            }

            if (Stop)
            {
                return;
            }

            Application.Current.Dispatcher.Invoke(() =>
            {
                try
                {
                    Results = allResults.ToDictionary(x => x.Key, x => x.Value);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error in single mouse viewmodel!!! " + e.InnerException);
                }
            });
        }