Exemplo n.º 1
0
        public static void RunSimulation(SimulationInput input, string outputFolderPath)
        {
            var mc = new MonteCarloSimulation(input);

            // locate root folder for output, creating it if necessary
            var path = string.IsNullOrEmpty(outputFolderPath)
                ? Path.GetFullPath(Directory.GetCurrentDirectory())
                : Path.GetFullPath(outputFolderPath);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // locate destination folder for output, creating it if necessary
            var resultsFolder = Path.Combine(path, input.OutputName);

            if (!Directory.Exists(resultsFolder))
            {
                Directory.CreateDirectory(resultsFolder);
            }

            mc.SetOutputPathForDatabases(path);

            SimulationOutput detectorResults = mc.Run();

            input.ToFile(Path.Combine(resultsFolder, input.OutputName + ".txt"));

            foreach (var result in detectorResults.ResultsDictionary.Values)
            {
                // save all detector data to the specified folder
                DetectorIO.WriteDetectorToFile(result, resultsFolder);
            }
        }
Exemplo n.º 2
0
        public void Run_simulations()
        {
            var featureValues = new[] {
                new[] { 1f, 2f, 3f }, // F 1
                new[] { 5f, 6f },     // F 2
                new[] { 10f, 20f, 30f, 40f } // F3
            };

            // Values to be selected from each feat. per simulation: (F1,F2,F3), ...
            // Values to be selected: (1f,5f,10f), (2f,6f,20f), (3f,6f,40f)
            // Simulation results expected: 16f, 28f, 49f
            // Indexes of values: 0,0,0, 1,1,1, 2,1,3
            var randomIndexes = new Queue <int>(new[] { 0, 0, 0, 1, 1, 1, 2, 1, 3 });
            var sut           = new MonteCarloSimulation(_ => randomIndexes.Dequeue());

            var result = sut.Run(3, featureValues);

            Assert.AreEqual(new[] { 16f, 28f, 49f }, result);
        }
Exemplo n.º 3
0
        public void validate_fluent_constructed_SimulationInput_runs_simulation_without_crashing()
        {
            var si = new SimulationInput("demoInput")
            {
                N = 30
            }
            .WithSourceInput(SourceInputProvider.DirectionalPointSourceInput())
            .WithTissueInput(TissueInputProvider.MultiLayerTissueInput())
            .WithDetectorInputs(DetectorInputProvider.RDiffuseDetectorInput());

            Assert.NotNull(si.SourceInput);
            Assert.NotNull(si.TissueInput);
            Assert.NotNull(si.DetectorInputs);
            Assert.IsTrue(si.DetectorInputs.Count == 1);

            var mc     = new MonteCarloSimulation(si);
            var output = mc.Run();

            Assert.NotNull(output);
            Assert.True(output.Input.N == 30);
        }
        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);
        }