private void PlotMuspSpectrum_Executed()
        {
            var            axisType   = IndependentVariableAxis.Wavelength;
            var            axisUnits  = IndependentVariableAxisUnits.NM;
            PlotAxesLabels axesLabels = new PlotAxesLabels(
                "μs'",
                "mm-1",
                new IndependentAxisViewModel
            {
                AxisType    = axisType,
                AxisLabel   = axisType.GetInternationalizedString(),
                AxisUnits   = axisUnits.GetInternationalizedString(),
                AxisRangeVM = WavelengthRangeVM
            });

            Commands.Plot_SetAxesLabels.Execute(axesLabels);

            var tissue      = SelectedTissue;
            var wavelengths = WavelengthRangeVM.Values.ToArray();
            var points      = new Point[wavelengths.Length];

            for (int wvi = 0; wvi < wavelengths.Length; wvi++)
            {
                var wavelength = wavelengths[wvi];
                points[wvi] = new Point(wavelength, tissue.GetMusp(wavelength));
            }

            Commands.Plot_PlotValues.Execute(new[] { new PlotData(points, "μs' spectra") });

            double minWavelength = WavelengthRangeVM.Values.Min();
            double maxWavelength = WavelengthRangeVM.Values.Max();

            Commands.TextOutput_PostMessage.Execute("Plotted μs' spectrum; wavelength range [nm]: [" + minWavelength + ", " + maxWavelength + "]\r");
        }
 private PlotAxesLabels GetPlotLabels()
 {
     var sd = this.SolutionDomainTypeOptionVM;
     PlotAxesLabels axesLabels = new PlotAxesLabels(
         sd.SelectedDisplayName, sd.SelectedValue.GetUnits(), 
         sd.IndependentAxesVMs.First(),
         sd.ConstantAxesVMs);
     return axesLabels;
 }
        private PlotAxesLabels GetPlotLabels()
        {
            var            sd         = this.SolutionDomainTypeOptionVM;
            PlotAxesLabels axesLabels = new PlotAxesLabels(
                sd.SelectedDisplayName, sd.SelectedValue.GetUnits(),
                sd.IndependentAxesVMs.Where(vm => vm.AxisType == AllRangeVMs.First().AxisType).First(),
                sd.ConstantAxesVMs);

            return(axesLabels);
        }
Ejemplo n.º 4
0
        private PlotAxesLabels GetPlotLabels()
        {
            var sd = GetSelectedSolutionDomain();

            PlotAxesLabels axesLabels = new PlotAxesLabels(
                sd.SelectedDisplayName, sd.SelectedValue.GetUnits(),
                sd.IndependentAxesVMs.First(),
                sd.ConstantAxesVMs);

            return(axesLabels);
        }
        private void CalculateInitialGuessCommand_Executed(object sender, ExecutedEventArgs e)
        {
            var initialGuessDataValues = CalculateInitialGuess();
            var initialGuessDataPoints = GetDataPoints(initialGuessDataValues);

            //Report the results
            PlotAxesLabels axesLabels = GetPlotLabels();
            Commands.Plot_SetAxesLabels.Execute(axesLabels);
            string[] plotLabels = GetLegendLabels(PlotDataType.Guess);
            var plotData = Enumerable.Zip(initialGuessDataPoints, plotLabels, (p, el) => new PlotData(p, el)).ToArray();
            Commands.Plot_PlotValues.Execute(plotData);
            Commands.TextOutput_PostMessage.Execute("Initial Guess: " + InitialGuessOpticalPropertyVM + " \r");
        }
        void SimulateMeasuredDataCommand_Executed(object sender, ExecutedEventArgs e)
        {
            var measuredDataValues = GetSimulatedMeasuredData();
            var measuredDataPoints = GetDataPoints(measuredDataValues);

            //Report the results
            PlotAxesLabels axesLabels = GetPlotLabels();
            Commands.Plot_SetAxesLabels.Execute(axesLabels);
            string[] plotLabels = GetLegendLabels(PlotDataType.Simulated);
            var plotData = Enumerable.Zip(measuredDataPoints, plotLabels, (p, el) => new PlotData(p, el)).ToArray();
            Commands.Plot_PlotValues.Execute(plotData);
            Commands.TextOutput_PostMessage.Execute("Simulated Measured Data: " + MeasuredOpticalPropertyVM + "\r");
        }
        void ExecuteForwardSolver_Executed(object sender, ExecutedEventArgs e)
        {
            IDataPoint[][] points     = ExecuteForwardSolver();
            PlotAxesLabels axesLabels = GetPlotLabels();

            Commands.Plot_SetAxesLabels.Execute(axesLabels);

            string[] plotLabels = GetLegendLabels();

            var plotData = Enumerable.Zip(points, plotLabels, (p, el) => new PlotData(p, el)).ToArray();

            Commands.Plot_PlotValues.Execute(plotData);

            Commands.TextOutput_PostMessage.Execute("Forward Solver: " + TissueInputVM + "\r"); // todo: override ToString() for MultiRegionTissueViewModel
        }
        private void SolveInverseCommand_Executed(object sender, ExecutedEventArgs e)
        {
            // Report inverse solver setup and results
            Commands.TextOutput_PostMessage.Execute("Inverse Solution Results: \r");
            Commands.TextOutput_PostMessage.Execute("   Optimization parameter(s): " + InverseFitTypeOptionVM.SelectedValue + " \r");
            Commands.TextOutput_PostMessage.Execute("   Initial Guess: " + InitialGuessOpticalPropertyVM + " \r");

            var inverseResult = SolveInverse();
            ResultOpticalPropertyVM.SetOpticalProperties(inverseResult.FitOpticalProperties.First()); // todo: this only works for one set of properties

            //Report the results
            if (SolutionDomainTypeOptionVM.IndependentVariableAxisOptionVM.SelectedValues.Contains(IndependentVariableAxis.Wavelength) && 
                inverseResult.FitOpticalProperties.Length > 1) // If multi-valued OPs, the results aren't in the "scalar" VMs, need to parse OPs directly
            {
                var fitOPs = inverseResult.FitOpticalProperties;
                var measuredOPs = inverseResult.MeasuredOpticalProperties;
                var wavelengths = GetParameterValues(IndependentVariableAxis.Wavelength);
                var wvUnitString = IndependentVariableAxisUnits.NM.GetInternationalizedString(); 
                var opUnitString = IndependentVariableAxisUnits.InverseMM.GetInternationalizedString();
                var sb = new StringBuilder("\t[Wavelength (" + wvUnitString + ")]\t\t\t\t\t\t[Exact]\t\t\t\t\t\t[At Converged Values]\t\t\t\t\t\t[Units]\r");
                for (int i = 0; i < fitOPs.Length; i++)
                {
                    sb.Append("\t" + wavelengths[i] + "\t\t\t\t\t\t" + measuredOPs[i] + "\t\t\t" + fitOPs[i] + "\t\t\t" + opUnitString + " \r");
                }
                Commands.TextOutput_PostMessage.Execute(sb.ToString());
            }
            else
            {
                Commands.TextOutput_PostMessage.Execute("   Exact: " + MeasuredOpticalPropertyVM + " \r");
                Commands.TextOutput_PostMessage.Execute("   At Converged Values: " + ResultOpticalPropertyVM + " \r");
            }

            PlotAxesLabels axesLabels = GetPlotLabels();
            Commands.Plot_SetAxesLabels.Execute(axesLabels);
            string[] plotLabels = GetLegendLabels(PlotDataType.Calculated);
            var plotData = Enumerable.Zip(inverseResult.FitDataPoints, plotLabels, (p, el) => new PlotData(p, el)).ToArray();
            Commands.Plot_PlotValues.Execute(plotData);
        }
        private void MC_ExecuteMonteCarloSolver_Executed(object sender, ExecutedEventArgs e)
        {
            if (!EnoughRoomInIsolatedStorage(50))
            {
                logger.Info(() => "\rSimulation not run. Please allocate more than 50MB of storage space.\r");
                Commands.IsoStorage_IncreaseSpaceQuery.Execute();
                return;
            }

            _newResultsAvailable = false;

            var input = _simulationInputVM.SimulationInput;


            var validationResult = SimulationInputValidation.ValidateInput(input);

            if (!validationResult.IsValid)
            {
                logger.Info(() => "\rSimulation input not valid.\rRule: " + validationResult.ValidationRule +
                            (!string.IsNullOrEmpty(validationResult.Remarks) ? "\rDetails: " + validationResult.Remarks : "") + ".\r");
                return;
            }

            _simulation = new MonteCarloSimulation(input);

            _currentCancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancelToken = _currentCancellationTokenSource.Token;
            TaskScheduler     scheduler   = TaskScheduler.FromCurrentSynchronizationContext();

            var t = Task.Factory.StartNew(() => _simulation.Run(), TaskCreationOptions.LongRunning);

            var c = t.ContinueWith((antecedent) =>
            {
                SolverDemoView.Current.Dispatcher.BeginInvoke(delegate()
                {
                    _output = antecedent.Result;
                    _newResultsAvailable = _simulation.ResultsAvailable;

                    var rOfRhoDetectorInputs = _simulationInputVM.SimulationInput.DetectorInputs.
                                               Where(di => di.Name == "ROfRho");

                    if (rOfRhoDetectorInputs.Any())
                    {
                        logger.Info(() => "Creating R(rho) plot...");

                        var detectorInput = (ROfRhoDetectorInput)rOfRhoDetectorInputs.First();

                        double[] independentValues = detectorInput.Rho.AsEnumerable().ToArray();

                        DoubleDataPoint[] points = null;

                        //var showPlusMinusStdev = true;
                        //if(showPlusMinusStdev && _output.R_r2 != null)
                        //{
                        //    var stdev = Enumerable.Zip(_output.R_r, _output.R_r2, (r, r2) => Math.Sqrt((r2 - r * r) / nPhotons)).ToArray();
                        //    var rMinusStdev = Enumerable.Zip(_output.R_r, stdev, (r,std) => r-std).ToArray();
                        //    var rPlusStdev = Enumerable.Zip(_output.R_r, stdev, (r,std) => r+std).ToArray();
                        //    points = Enumerable.Zip(
                        //        independentValues.Concat(independentValues).Concat(independentValues),
                        //        rMinusStdev.Concat(_output.R_r).Concat(rPlusStdev),
                        //        (x, y) => new Point(x, y));
                        //}
                        //else
                        //{
                        points = Enumerable.Zip(
                            independentValues,
                            _output.R_r,
                            (x, y) => new DoubleDataPoint(x, y)).ToArray();
                        //}

                        PlotAxesLabels axesLabels = GetPlotLabels();
                        Commands.Plot_SetAxesLabels.Execute(axesLabels);

                        string plotLabel = GetPlotLabel();
                        Commands.Plot_PlotValues.Execute(new[] { new PlotData(points, plotLabel) });
                        logger.Info(() => "done.\r");
                    }

                    var fluenceDetectorInputs = _simulationInputVM.SimulationInput.DetectorInputs.
                                                Where(di => di.Name == "FluenceOfRhoAndZ");

                    if (fluenceDetectorInputs.Any())
                    {
                        logger.Info(() => "Creating Fluence(rho,z) map...");
                        var detectorInput = (FluenceOfRhoAndZDetectorInput)fluenceDetectorInputs.First();
                        var rhosMC        = detectorInput.Rho.AsEnumerable().ToArray();
                        var zsMC          = detectorInput.Z.AsEnumerable().ToArray();

                        var rhos = Enumerable.Zip(rhosMC.Skip(1), rhosMC.Take(rhosMC.Length - 1), (first, second) => (first + second) / 2).ToArray();
                        var zs   = Enumerable.Zip(zsMC.Skip(1), rhosMC.Take(zsMC.Length - 1), (first, second) => (first + second) / 2).ToArray();

                        var dRhos = Enumerable.Select(rhos, rho => 2 * Math.PI * Math.Abs(rho) * detectorInput.Rho.Delta).ToArray();
                        var dZs   = Enumerable.Select(zs, z => detectorInput.Z.Delta).ToArray();

                        if (_mapArrayBuffer == null || _mapArrayBuffer.Length != _output.Flu_rz.Length * 2)
                        {
                            _mapArrayBuffer = new double[_output.Flu_rz.Length * 2];
                        }

                        // flip the array (since it goes over zs and then rhos, while map wants rhos and then zs
                        for (int zi = 0; zi < zs.Length; zi++)
                        {
                            for (int rhoi = 0; rhoi < rhos.Length; rhoi++)
                            {
                                _mapArrayBuffer[rhoi + rhos.Length + rhos.Length * 2 * zi] = _output.Flu_rz[rhoi, zi];
                            }
                            var localRhoiForReverse = 0;
                            for (int rhoi = rhos.Length - 1; rhoi >= 0; rhoi--, localRhoiForReverse++)
                            {
                                _mapArrayBuffer[localRhoiForReverse + rhos.Length * 2 * zi] = _output.Flu_rz[rhoi, zi];
                            }
                        }

                        var twoRhos  = Enumerable.Concat(rhos.Reverse().Select(rho => - rho), rhos).ToArray();
                        var twoDRhos = Enumerable.Concat(dRhos.Reverse(), dRhos).ToArray();

                        var mapData = new MapData(_mapArrayBuffer, twoRhos, zs, twoDRhos, dZs);

                        Commands.Maps_PlotMap.Execute(mapData);
                        logger.Info(() => "done.\r");
                    }

                    // save results to isolated storage
                    logger.Info(() => "Saving simulation results to temporary directory...");
                    //var detectorFolder = Path.Combine(TEMP_RESULTS_FOLDER, input.OutputName);

                    //// create the root directory
                    //FileIO.CreateDirectory(TEMP_RESULTS_FOLDER);
                    // create the detector directory, removing stale files first if they exist
                    FileIO.CreateEmptyDirectory(TEMP_RESULTS_FOLDER);

                    // write detector to file
                    input.ToFile(Path.Combine(TEMP_RESULTS_FOLDER, "infile_" + input.OutputName + ".txt"));
                    foreach (var result in _output.ResultsDictionary.Values)
                    {
                        // save all detector data to the specified folder
                        DetectorIO.WriteDetectorToFile(result, TEMP_RESULTS_FOLDER);
                    }

                    var store = IsolatedStorageFile.GetUserStoreForApplication();
                    if (store.DirectoryExists(TEMP_RESULTS_FOLDER))
                    {
                        var currentAssembly = Assembly.GetExecutingAssembly();
                        // get all the files we want to zip up
                        var fileNames = store.GetFileNames(TEMP_RESULTS_FOLDER + @"\*");
                        // copy the MATLAB files to isolated storage and get their names so they can be included in the zip file
                        var matlabFiles = FileIO.CopyFolderFromEmbeddedResources("Matlab", TEMP_RESULTS_FOLDER, currentAssembly.FullName, false);
                        // then, zip all the files together and store *that* .zip to isolated storage as well (can't automatically copy to user folder due to security restrictions)
                        var allFiles = matlabFiles.Concat(fileNames).Distinct();
                        try
                        {
                            FileIO.ZipFiles(allFiles, TEMP_RESULTS_FOLDER, input.OutputName + ".zip");
                        }
                        catch (SecurityException)
                        {
                            logger.Error(() => "\rProblem saving results to file.\r");
                        }
                    }
                    logger.Info(() => "done.\r");
                });
            },
                                   cancelToken,
                                   TaskContinuationOptions.OnlyOnRanToCompletion,
                                   scheduler);
        }