public ActionResult MonteCarloSimulationModal(int id)
        {
            MonteCarloSimulationDto model = new MonteCarloSimulationDto();

            if (id == 0)
            {
                TradingAccountDto tradingAccount = this._tradingAccountAppService.GetActive();
                List <Market>     markets        = this._marketRepository.GetAll().Where(x => x.Active).ToList();

                model.TimeStamp                  = DateTime.Now;
                model.TradingAccountId           = tradingAccount.Id;
                model.NumberOfTradesInSample     = this._tradeRepository.GetAll().Count(x => x.TradingAccountId == model.TradingAccountId && x.ExitReason != TradeExitReasons.None);
                model.NumberOfTradesPerIteration = 30;
                model.NumberOfIterations         = 1000;
                model.CumulativeProfitK          = .95m;
                model.ConsecutiveLossesK         = 1m;
                model.MaxDrawdownK               = .99m;
                model.AccountSize                = tradingAccount.CurrentCapital;
                model.RuinPoint                  = markets.Average(x => x.InitialMargin) + 10m;
                model.MaxDrawdownMultiple        = 2m;
            }
            else
            {
                MonteCarloSimulation monteCarloSimulation = this._repository.Single(x => x.Id == id);
                monteCarloSimulation.MapTo(model);
            }

            return(PartialView("Modals/_MonteCarloSimulationModal", model));
        }
示例#2
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);
            }
        }
示例#3
0
        public void validate_photon_database_postprocessor_ROfRhoAndTime_results()
        {
            // DAW postprocssing
            var DAWinput          = GenerateReferenceDAWInput();
            var onTheFlyDAWOutput = new MonteCarloSimulation(DAWinput).Run();

            var DAWdatabase      = PhotonDatabase.FromFile("DiffuseReflectanceDatabase");
            var DAWpostProcessor = new PhotonDatabasePostProcessor(
                VirtualBoundaryType.DiffuseReflectance,
                _detectorInputs,
                DAWdatabase,
                onTheFlyDAWOutput.Input);
            var postProcessedDAWOutput = DAWpostProcessor.Run();

            ValidateROfRhoAndTime(onTheFlyDAWOutput, postProcessedDAWOutput);

            // CAW postprocessing
            var CAWinput          = GenerateReferenceCAWInput();
            var onTheFlyCAWOutput = new MonteCarloSimulation(CAWinput).Run();

            var CAWdatabase      = PhotonDatabase.FromFile("DiffuseReflectanceDatabase");
            var CAWpostProcessor = new PhotonDatabasePostProcessor(
                VirtualBoundaryType.DiffuseReflectance,
                _detectorInputs,
                CAWdatabase,
                onTheFlyCAWOutput.Input);
            var postProcessedCAWOutput = CAWpostProcessor.Run();

            ValidateROfRhoAndTime(onTheFlyCAWOutput, postProcessedCAWOutput);
        }
        public void GetMoveParallel_Simulation_()
        {
            var map   = MapTest.Map18;
            var state = State.Create(map);

            var simParallel = new MonteCarloSimulation(17, true);
            var act         = simParallel.GetMove(map, PlayerType.Hero1, state, SimulationTime, 300);

            Console.WriteLine("{0:#,##0.00}k/s (Parallel)", simParallel.Simulations / SimulationTime.TotalMilliseconds);
        }
示例#5
0
        public void GetMoveParallel_Simulation_()
        {
            var state = State.Create(MapTest.Map16);

            var simParallel = new MonteCarloSimulation(17, true);
            var act         = simParallel.GetMove(MapTest.Map16, state, SimulationTime);

            Console.WriteLine("{0:#,##0.00}k/s (Parallel)", simParallel.Simulations / SimulationTime.TotalMilliseconds);

            Assert.AreEqual(MoveDirection.E, act);
        }
        public void RunSimulation(MonteCarloSimulationDto dto)
        {
            MonteCarloSimulation sim = _repository.Get(dto.Id);

            sim.MapTo(dto);
            List <Trade>  sample  = this._tradeRepository.GetAll().Where(x => x.TradingAccountId == dto.TradingAccountId && x.ExitReason != TradeExitReasons.None).ToList();
            List <Market> markets = this._marketRepository.GetAll().Where(x => x.Active).ToList();

            dto.Simulate(sample, markets, this._consoleHubProxy);
            dto.MapTo(sim);
        }
示例#7
0
        public void Run()
        {
            var data = new[] {
                1,
                1,
                1,
                1,
                1,
                1,
                1,
                1,
                1,
                1,
                2,
                2,
                2,
                2,
                2,
                3,
                3,
                3,
                4,
                4,
                5,
                6,
                7,
                8,
                9,
                10,
                11,
                15,
                15,
                15
            };

            var dist = Statistics.Distribution(data);
            var deDE = new CultureInfo("de-DE");

            foreach (var x in dist.OrderBy(o => o.value))
            {
                _testOutputHelper.WriteLine($"{x.value}\t{x.frequency}\t{x.probability.ToString("0.000", deDE)}\t{x.percentile.ToString("0.0", deDE)}");
            }


            var mcs     = new MonteCarloSimulation <int, int>(values => values.Sum());
            var results = mcs.Simulate(data, data, data, data, data);

            _testOutputHelper.WriteLine("---");
            dist = Statistics.Distribution(results);
            foreach (var x in dist.OrderBy(o => o.value))
            {
                _testOutputHelper.WriteLine($"{x.value}\t{x.frequency}\t{x.probability.ToString("0.000", deDE)}\t{x.percentile.ToString("0.0", deDE)}");
            }
        }
示例#8
0
        public void GetMove_Performance_()
        {
            var state = State.Create(MapTest.Map16);

            var simSingle = new MonteCarloSimulation(17, false);

            var time = TimeSpan.FromSeconds(2);

            var moveSingle = simSingle.GetMove(MapTest.Map16, state, time);

            Console.WriteLine("{0:#,##0.00}k/s (Single)", simSingle.Simulations / time.TotalMilliseconds);
        }
示例#9
0
        public void Build_random_number_generator()
        {
            var sut = MonteCarloSimulation.Build_random_number_generator();

            const int MAX = 10;

            for (var i = 0; i < 100; i++)
            {
                var r = sut(MAX);
                Assert.IsTrue(r <= (MAX - 1));

                Console.WriteLine(r);
            }
        }
        public double HW_CAP_CM(double t0, double tAlpha, double[] taoArray, double x, double n, int num)
        {
            // 3.37
            Func <double, double> alphaFunc = t => MarketF(t) +
                                              Pow(this.Sigma(), 2) / (2 * Pow(this.A(), 2)) *
                                              Pow(1 - Exp(-this.A() * t), 2);
            var mu = MarketF(0) * Exp(-this.A() * t0) + alphaFunc(t0) -
                     alphaFunc(0) * Exp(-this.A() * t0);
            var sigma = Pow(this.Sigma(), 2) / (2 * Pow(this.A(), 2)) *
                        Pow(1 - Exp(-2 * this.A() * t0), 2);
            var sampleFunc = MonteCarloSimulation.GenerateSamples(
                num, 0.Wrap(), (t, rt) => HW_Caps(t0, tAlpha, taoArray, x, n, rt), mu.Wrap(), sigma.Wrap());
            var samples = sampleFunc();

            return(samples.Average());
        }
 public void Save(MonteCarloSimulationDto dto)
 {
     if (dto.IsNew)
     {
         MonteCarloSimulation monteCarloSimulation = dto.MapTo <MonteCarloSimulation>();
         int id = this._repository.InsertAndGetId(monteCarloSimulation);
         this.RunSimulationEnqueue(new MonteCarloSimulationDto()
         {
             Id = id
         });
     }
     else
     {
         MonteCarloSimulation monteCarloSimulation = this._repository.Get(dto.Id);
         dto.MapTo(monteCarloSimulation);
     }
 }
示例#12
0
        public void validate_RunAll_given_two_simulations_runs_without_crashing()
        {
            var si1 = new SimulationInput {
                N = 30
            };
            var si2 = new SimulationInput {
                N = 20
            };
            var sim1 = new MonteCarloSimulation(si1);
            var sim2 = new MonteCarloSimulation(si2);
            var sims = new[] { sim1, sim2 };

            var outputs = MonteCarloSimulation.RunAll(sims);

            Assert.NotNull(outputs[0]);
            Assert.NotNull(outputs[1]);
            Assert.True(outputs[0].Input.N == 30);
            Assert.True(outputs[1].Input.N == 20);
        }
示例#13
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);
        }
示例#14
0
        public void MonteCarlo(double[] data, string key, int span, int index)
        {
            double[] daSubData = data;

            if (index != data.Length - 1)
            {
                daSubData = data.Take(index + 1).ToArray();
            }


            //if (!MonteCarloData.ContainsKey(key))
            MonteCarloData.Add(key, new ThreadedList <double[]>());

            try
            {
                for (int i = 0; i < 1000000; i++)
                {
                    MonteCarloData[key].Add(MonteCarloSimulation.Next(daSubData, span).ToArray());


                    while (Performance.CPU > 50)
                    {
                        Thread.Sleep(1);
                        if (StopSimulations)
                        {
                            return;
                        }
                    }

                    //while (Performance.CPU > 50 && Performance.CPU < 100)
                    //    if (!this.Sleep(Indexes.Length)) return;

                    if (StopSimulations)
                    {
                        return;
                    }
                    //
                }
            }
            catch { }
        }
示例#15
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);
        }
示例#16
0
        public void validate_database_input_with_no_detectors_specified_still_generates_database()
        {
            // make sure databases generated from previous tests are deleted
            if (FileIO.FileExists("DiffuseReflectanceDatabase.txt"))
            {
                FileIO.FileDelete("DiffuseReflectanceDatabase.txt");
            }
            if (FileIO.FileExists("DiffuseReflectanceDatabase"))
            {
                FileIO.FileDelete("DiffuseReflectanceDatabase");
            }
            var input = new SimulationInput(
                100,
                "", // can't give folder name when writing to isolated storage
                new SimulationOptions(
                    0,
                    RandomNumberGeneratorType.MersenneTwister,
                    AbsorptionWeightingType.Discrete,
                    PhaseFunctionType.HenyeyGreenstein,
                    new List <DatabaseType>()
            {
                DatabaseType.DiffuseReflectance
            },             // SPECIFY DATABASE
                    false, // track statistics
                    0.0,   // RR threshold -> 0 = no RR performed
                    1),
                _sourceInput,
                _tissueInput,
                new List <IDetectorInput>()
            {
            }                                 // specify NO DETECTORS
                );
            var output = new MonteCarloSimulation(input).Run();

            Assert.IsTrue(FileIO.FileExists("DiffuseReflectanceDatabase"));
            Assert.IsFalse(FileIO.FileExists("DiffuseTransmittanceDatabase"));
        }
        private double[] HW_R_CM(double s, double rs, double t0, int n)
        {
            // 3.37
            if (t0 == s)
            {
                return new[] { rs }
            }
            ;
            var sigma = this.Sigma();
            var a     = this.A();

            double AlphaFunc(double t) => MarketF(t) +
            Pow(sigma, 2) / (2 * Pow(a, 2)) * Pow(1 - Exp(-a * t), 2);

            var mu = rs * Exp(-a * (t0 - s)) + AlphaFunc(t0) -
                     AlphaFunc(s) * Exp(-a * (t0 - s));
            var stdvar = Pow(sigma, 2) / (2 * Pow(a, 2)) *
                         Pow(1 - Exp(-2 * a * (t0 - s)), 2);
            var sampleFunc = MonteCarloSimulation.GenerateSamples(
                n, 0.Wrap(), (t, x) => x, mu.Wrap(), stdvar.Wrap());
            var samples = sampleFunc();

            return(samples);
        }
        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);
        }
示例#19
0
        public void execute_Monte_Carlo()
        {
            // instantiate common classes
            var simulationOptions = new SimulationOptions(
                0,
                RandomNumberGeneratorType.MersenneTwister,
                AbsorptionWeightingType.Discrete,
                PhaseFunctionType.HenyeyGreenstein,
                new List <DatabaseType>()
            {
                DatabaseType.pMCDiffuseReflectance
            },         // write database for pMC tests
                false, // track statistics
                0.0,   // RR threshold -> 0 = no RR performed
                0);
            var source = new DirectionalPointSourceInput(
                new Position(0.0, 0.0, 0.0),
                new Direction(0.0, 0.0, 1.0),
                0);      // start in air
            var tissue = new MultiLayerTissueInput(
                new ITissueRegion[]
            {
                new LayerTissueRegion(
                    new DoubleRange(double.NegativeInfinity, 0.0),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0)),
                new LayerTissueRegion(
                    new DoubleRange(0.0, 10.0),     // make tissue layer thin so transmittance results improved
                    new OpticalProperties(0.01, 1.0, 0.8, 1.4)),
                new LayerTissueRegion(
                    new DoubleRange(10.0, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            });
            var detectorsNA0 = new List <IDetectorInput>
            {
                new RDiffuseDetectorInput()
                {
                    FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfAngleDetectorInput()
                {
                    Angle = new DoubleRange(Math.PI / 2, Math.PI, 2), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfRhoDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfRhoAndAngleDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Angle = new DoubleRange(Math.PI / 2, Math.PI, 2), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfRhoAndTimeDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Time = new DoubleRange(0.0, 1.0, 11), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfRhoAndOmegaDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Omega = new DoubleRange(0.05, 1.0, 20), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfXAndYDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfXAndYAndTimeDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), Time = new DoubleRange(0, 1, 11), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfXAndYAndMaxDepthDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), MaxDepth = new DoubleRange(0, 10.0, 11), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfFxDetectorInput()
                {
                    Fx = new DoubleRange(0.0, 0.5, 51), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new ROfFxAndTimeDetectorInput()
                {
                    Fx = new DoubleRange(0.0, 0.5, 51), Time = new DoubleRange(0.0, 1.0, 11), FinalTissueRegionIndex = 0, NA = 0.0
                },
                new RSpecularDetectorInput()
                {
                    FinalTissueRegionIndex = 0, NA = 0.0
                },
                new TDiffuseDetectorInput()
                {
                    FinalTissueRegionIndex = 2, NA = 0.0
                },
                new TOfAngleDetectorInput()
                {
                    Angle = new DoubleRange(0.0, Math.PI / 2, 2), FinalTissueRegionIndex = 2, NA = 0.0
                },
                new TOfRhoAndAngleDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Angle = new DoubleRange(0.0, Math.PI / 2, 2), FinalTissueRegionIndex = 2, NA = 0.0
                },
                new TOfRhoDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), FinalTissueRegionIndex = 2, NA = 0.0
                },
                new TOfXAndYDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), FinalTissueRegionIndex = 2, NA = 0.0
                },
                new RadianceOfRhoAtZDetectorInput()
                {
                    ZDepth = _dosimetryDepth, Rho = new DoubleRange(0.0, 10.0, 11), FinalTissueRegionIndex = 1, NA = 0.0
                },

                new ReflectedMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                    = new DoubleRange(0.0, 10.0, 11),
                    MTBins                 = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins       = new DoubleRange(0.0, 1.0, 11),
                    FinalTissueRegionIndex = 0,
                    NA = 0.0
                },
                new ReflectedMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                      = new DoubleRange(-10.0, 10.0, 11),
                    Y                      = new DoubleRange(-10.0, 10.0, 11),
                    MTBins                 = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins       = new DoubleRange(0.0, 1.0, 11),
                    FinalTissueRegionIndex = 0,
                    NA                     = 0.0
                },
                new TransmittedMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                    = new DoubleRange(0.0, 10.0, 11),
                    MTBins                 = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins       = new DoubleRange(0.0, 1.0, 11),
                    FinalTissueRegionIndex = 2,
                    NA = 0.0
                },
                new TransmittedMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                      = new DoubleRange(-10.0, 10.0, 11),
                    Y                      = new DoubleRange(-10.0, 10.0, 11),
                    MTBins                 = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins       = new DoubleRange(0.0, 1.0, 11),
                    FinalTissueRegionIndex = 2,
                    NA                     = 0.0
                },
            };
            var input = new SimulationInput(
                100,
                "",
                simulationOptions,
                source,
                tissue,
                detectorsNA0);

            _outputNA0 = new MonteCarloSimulation(input).Run();

            _inputForPMC = input;                                                                       // set pMC input to one that specified database generation
            _pMCDatabase = pMCDatabase.FromFile("DiffuseReflectanceDatabase", "CollisionInfoDatabase"); // grab database


            var detectorsNA0p3 = new List <IDetectorInput>
            {
                new RDiffuseDetectorInput()
                {
                    FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfAngleDetectorInput()
                {
                    Angle = new DoubleRange(Math.PI / 2, Math.PI, 2), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfRhoDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfRhoAndAngleDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Angle = new DoubleRange(Math.PI / 2, Math.PI, 2), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfRhoAndTimeDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Time = new DoubleRange(0.0, 1.0, 11), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfRhoAndOmegaDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Omega = new DoubleRange(0.05, 1.0, 20), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfXAndYDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfXAndYAndTimeDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), Time = new DoubleRange(0, 1, 11), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfXAndYAndMaxDepthDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), MaxDepth = new DoubleRange(0, 10.0, 11), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfFxDetectorInput()
                {
                    Fx = new DoubleRange(0.0, 0.5, 51), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfFxAndTimeDetectorInput()
                {
                    Fx = new DoubleRange(0.0, 0.5, 5), Time = new DoubleRange(0.0, 1.0, 11), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new RSpecularDetectorInput()
                {
                    FinalTissueRegionIndex = 0, NA = 0.3
                },
                new TDiffuseDetectorInput()
                {
                    FinalTissueRegionIndex = 2, NA = 0.3
                },
                new TOfAngleDetectorInput()
                {
                    Angle = new DoubleRange(0.0, Math.PI / 2, 2), FinalTissueRegionIndex = 2, NA = 0.3
                },
                new TOfRhoAndAngleDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Angle = new DoubleRange(0.0, Math.PI / 2, 2), FinalTissueRegionIndex = 2, NA = 0.3
                },
                new TOfRhoDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), FinalTissueRegionIndex = 2, NA = 0.3
                },
                new TOfXAndYDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), FinalTissueRegionIndex = 2, NA = 0.3
                },

                new RadianceOfRhoAtZDetectorInput()
                {
                    ZDepth = _dosimetryDepth, Rho = new DoubleRange(0.0, 10.0, 11), FinalTissueRegionIndex = 1, NA = 0.3
                },

                new ReflectedMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                    = new DoubleRange(0.0, 10.0, 11),
                    MTBins                 = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins       = new DoubleRange(0.0, 1.0, 11),
                    FinalTissueRegionIndex = 0,
                    NA = 0.3
                },
                new ReflectedMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                      = new DoubleRange(-10.0, 10.0, 11),
                    Y                      = new DoubleRange(-10.0, 10.0, 11),
                    MTBins                 = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins       = new DoubleRange(0.0, 1.0, 11),
                    FinalTissueRegionIndex = 0,
                    NA                     = 0.3
                },
                new TransmittedMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                    = new DoubleRange(0.0, 10.0, 11),
                    MTBins                 = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins       = new DoubleRange(0.0, 1.0, 11),
                    FinalTissueRegionIndex = 2,
                    NA = 0.3
                },
                new TransmittedMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                      = new DoubleRange(-10.0, 10.0, 11),
                    Y                      = new DoubleRange(-10.0, 10.0, 11),
                    MTBins                 = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins       = new DoubleRange(0.0, 1.0, 11),
                    FinalTissueRegionIndex = 2,
                    NA                     = 0.3
                },
            };

            input = new SimulationInput(
                100,
                "",
                simulationOptions,
                source,
                tissue,
                detectorsNA0p3);
            _outputNA0p3 = new MonteCarloSimulation(input).Run();

            var detectorsNoNASpecified = new List <IDetectorInput>
            {
                new RDiffuseDetectorInput()
                {
                },
                new ROfAngleDetectorInput()
                {
                    Angle = new DoubleRange(Math.PI / 2, Math.PI, 2)
                },
                new ROfRhoDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11)
                },
                new ROfRhoAndAngleDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Angle = new DoubleRange(Math.PI / 2, Math.PI, 2)
                },
                new ROfRhoAndTimeDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Time = new DoubleRange(0.0, 1.0, 11)
                },
                new ROfRhoAndOmegaDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Omega = new DoubleRange(0.05, 1.0, 20)
                },
                new ROfXAndYDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11)
                },
                new ROfXAndYAndTimeDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), Time = new DoubleRange(0, 1, 11), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfXAndYAndMaxDepthDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11), MaxDepth = new DoubleRange(0, 10.0, 11), FinalTissueRegionIndex = 0, NA = 0.3
                },
                new ROfFxDetectorInput()
                {
                    Fx = new DoubleRange(0.0, 0.5, 51)
                },
                new ROfFxAndTimeDetectorInput()
                {
                    Fx = new DoubleRange(0.0, 0.5, 5), Time = new DoubleRange(0.0, 1.0, 11)
                },
                new RSpecularDetectorInput()
                {
                },
                new TDiffuseDetectorInput()
                {
                },
                new TOfAngleDetectorInput()
                {
                    Angle = new DoubleRange(0.0, Math.PI / 2, 2)
                },
                new TOfRhoAndAngleDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11), Angle = new DoubleRange(0.0, Math.PI / 2, 2)
                },
                new TOfRhoDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 10.0, 11)
                },
                new TOfXAndYDetectorInput()
                {
                    X = new DoubleRange(-10.0, 10.0, 11), Y = new DoubleRange(-10.0, 10.0, 11)
                },

                new RadianceOfRhoAtZDetectorInput()
                {
                    ZDepth = _dosimetryDepth, Rho = new DoubleRange(0.0, 10.0, 11)
                },

                new ReflectedMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho              = new DoubleRange(0.0, 10.0, 11),
                    MTBins           = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins = new DoubleRange(0.0, 1.0, 11),
                },
                new ReflectedMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                = new DoubleRange(-10.0, 10.0, 11),
                    Y                = new DoubleRange(-10.0, 10.0, 11),
                    MTBins           = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins = new DoubleRange(0.0, 1.0, 11),
                },
                new TransmittedMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho              = new DoubleRange(0.0, 10.0, 11),
                    MTBins           = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins = new DoubleRange(0.0, 1.0, 11),
                },
                new TransmittedMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                = new DoubleRange(-10.0, 10.0, 11),
                    Y                = new DoubleRange(-10.0, 10.0, 11),
                    MTBins           = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins = new DoubleRange(0.0, 1.0, 11),
                },
            };

            input = new SimulationInput(
                100,
                "",
                simulationOptions,
                source,
                tissue,
                detectorsNoNASpecified);
            _outputNoNASpecified = new MonteCarloSimulation(input).Run();
        }
示例#20
0
        public void execute_Monte_Carlo()
        {
            // instantiate common classes
            _simulationOptions = new SimulationOptions(
                0,
                RandomNumberGeneratorType.MersenneTwister,
                AbsorptionWeightingType.Discrete,
                PhaseFunctionType.HenyeyGreenstein,
                new List <DatabaseType>(),
                false, // track statistics
                0.0,   // RR threshold -> 0 = no RR performed
                0);
            _source = new DirectionalPointSourceInput(
                new Position(0.0, 0.0, 0.0),
                new Direction(0.0, 0.0, 1.0),
                1);

            _tissue =
                new MultiLayerWithSurfaceFiberTissueInput(
                    new SurfaceFiberTissueRegion(
                        new Position(0, 0, 0),
                        _detectorRadius, // needs to match SurfaceFiberDetectorInput
                        new OpticalProperties(0.01, 1.0, 0.8, 1.4)
                        ),
                    new ITissueRegion[]
            {
                new LayerTissueRegion(
                    new DoubleRange(double.NegativeInfinity, 0.0),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0)),
                new LayerTissueRegion(
                    new DoubleRange(0.0, 100.0),
                    new OpticalProperties(0.01, 1.0, 0.8, 1.4)),
                new LayerTissueRegion(
                    new DoubleRange(100.0, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            }
                    );
            // tissue specification to verify MultiLayerWithSurfaceFiberTissue
            // increases reflectance.  If use this tissue need to change FinalTissueRegion
            // for ALL detectors to 0
            //new MultiLayerTissueInput(
            //    new ITissueRegion[]
            //    {
            //        new LayerTissueRegion(
            //            new DoubleRange(double.NegativeInfinity, 0.0),
            //            new OpticalProperties(0.0, 1e-10, 1.0, 1.0)),
            //        new LayerTissueRegion(
            //            new DoubleRange(0.0, 100.0),
            //            new OpticalProperties(0.01, 1.0, 0.8, 1.4)),
            //        new LayerTissueRegion(
            //            new DoubleRange(100.0, double.PositiveInfinity),
            //            new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            //    }
            //);

            _detectorOpen = new List <IDetectorInput>
            {
                new SurfaceFiberDetectorInput()
                {
                    Center            = new Position(0, 0, 0),
                    Radius            = _detectorRadius,
                    TallySecondMoment = true,
                    N  = 1.4,
                    NA = 1.4,
                    FinalTissueRegionIndex = 3
                },
                new ROfRhoDetectorInput() // 1mm wide ring to match fiber and 2 because beyond goes into 2nd
                {
                    Rho = new DoubleRange(0.0, 2 * _detectorRadius, 3),
                    // since tissue w fiber specified -> photon will be in 3 upon exit
                    FinalTissueRegionIndex = 3,
                    NA = 1.4,
                    TallySecondMoment = true
                },
            };
            _detectorNA = new List <IDetectorInput>
            {
                new SurfaceFiberDetectorInput()
                {
                    Center            = new Position(0, 0, 0),
                    Radius            = _detectorRadius,
                    TallySecondMoment = true,
                    N = 1.4,
                    FinalTissueRegionIndex = 3,
                    NA = 0.39
                },
                new ROfRhoDetectorInput() // ring to match fiber detector
                {
                    Rho = new DoubleRange(0.0, 2 * _detectorRadius, 3),
                    // since tissue w fiber specified -> photon will be in 3 upon exit
                    FinalTissueRegionIndex = 3,
                    NA = 0.39,
                    TallySecondMoment = true
                },
            };
            _detectorNAOffCenter = new List <IDetectorInput>
            {
                new SurfaceFiberDetectorInput()
                {
                    Center            = new Position(_detectorRadius, 0, 0), // diam = [0, 2*radius]
                    Radius            = _detectorRadius,
                    TallySecondMoment = true,
                    N = 1.4,
                    FinalTissueRegionIndex = 3,
                    NA = 1.4
                },
                new ROfRhoDetectorInput() // ring to match fiber detector
                {
                    // place 1st rho bin center at _detectorRadius with width = 2*radius
                    Rho = new DoubleRange(_detectorRadius / 2, 2 * _detectorRadius + _detectorRadius / 2, 3),
                    // since tissue w fiber specified -> photon will be in 3 upon exit
                    FinalTissueRegionIndex = 3,
                    NA = 1.4,
                    TallySecondMoment = true
                },
            };
            var _inputOpen = new SimulationInput(
                100,
                "",
                _simulationOptions,
                _source,
                _tissue,
                _detectorOpen);

            _outputOpen = new MonteCarloSimulation(_inputOpen).Run();

            var _inputNA = new SimulationInput(
                100,
                "",
                _simulationOptions,
                _source,
                _tissue,
                _detectorNA);

            _outputNA = new MonteCarloSimulation(_inputNA).Run();

            var _inputNAOffCenter = new SimulationInput(
                100,
                "",
                _simulationOptions,
                _source,
                _tissue,
                _detectorNAOffCenter);

            _outputNAOffCenter = new MonteCarloSimulation(_inputNAOffCenter).Run();
        }
示例#21
0
        public void execute_Monte_Carlo()
        {
            // instantiate common classes
            var simulationOptions = new SimulationOptions(
                0,
                RandomNumberGeneratorType.MersenneTwister,
                AbsorptionWeightingType.Discrete,
                PhaseFunctionType.HenyeyGreenstein,
                new List <DatabaseType>()
            {
            },
                false, // track statistics
                0.0,   // RR threshold -> 0 = no RR performed
                0);
            var source = new DirectionalPointSourceInput(
                new Position(0.0, 0.0, 0.0),
                new Direction(0.0, 0.0, 1.0),
                0);      // start in air
            var tissue = new MultiLayerTissueInput(
                new ITissueRegion[]
            {
                new LayerTissueRegion(
                    new DoubleRange(double.NegativeInfinity, 0.0),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0)),
                new LayerTissueRegion(
                    new DoubleRange(0.0, 10.0),     // make tissue layer thin so transmittance results improved
                    new OpticalProperties(0.01, 1.0, 0.8, 1.4)),
                new LayerTissueRegion(
                    new DoubleRange(10.0, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            });
            var detectorsNA0 = new List <IDetectorInput>
            {
                new ReflectedDynamicMTOfFxAndSubregionHistDetectorInput()
                {
                    Fx                  = new DoubleRange(0.0, 0.5, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 0,
                    NA = 0.0
                },
                new TransmittedDynamicMTOfFxAndSubregionHistDetectorInput()
                {
                    Fx                  = new DoubleRange(0.0, 0.5, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 2,
                    NA = 0.0
                },
                new ReflectedDynamicMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                 = new DoubleRange(0.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 0,
                    NA = 0.0
                },
                new TransmittedDynamicMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                 = new DoubleRange(0.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 2,
                    NA = 0.0
                },
                new ReflectedDynamicMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                   = new DoubleRange(-10.0, 10.0, 11),
                    Y                   = new DoubleRange(-10.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 21),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 0,
                    NA = 0.0
                },
                new TransmittedDynamicMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                   = new DoubleRange(-10.0, 10.0, 11),
                    Y                   = new DoubleRange(-10.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 2,
                    NA = 0.0
                }
            };
            var input = new SimulationInput(
                100,
                "",
                simulationOptions,
                source,
                tissue,
                detectorsNA0);

            _outputNA0 = new MonteCarloSimulation(input).Run();

            var detectorsNA0p3 = new List <IDetectorInput>
            {
                new ReflectedDynamicMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                 = new DoubleRange(0.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 0,
                    NA = 0.3
                },
                new TransmittedDynamicMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                 = new DoubleRange(0.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 2,
                    NA = 0.3
                },
                new ReflectedDynamicMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                   = new DoubleRange(-10.0, 10.0, 11),
                    Y                   = new DoubleRange(-10.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 21),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 0,
                    NA = 0.3
                },
                new TransmittedDynamicMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                   = new DoubleRange(-10.0, 10.0, 11),
                    Y                   = new DoubleRange(-10.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                    FinalTissueRegionIndex = 2,
                    NA = 0.3
                }
            };

            input = new SimulationInput(
                100,
                "",
                simulationOptions,
                source,
                tissue,
                detectorsNA0p3);
            _outputNA0p3 = new MonteCarloSimulation(input).Run();

            var detectorsNoNASpecified = new List <IDetectorInput>
            {
                new ReflectedDynamicMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                 = new DoubleRange(0.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                },
                new TransmittedDynamicMTOfRhoAndSubregionHistDetectorInput()
                {
                    Rho                 = new DoubleRange(0.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                },
                new ReflectedDynamicMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                   = new DoubleRange(-10.0, 10.0, 11),
                    Y                   = new DoubleRange(-10.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 21),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                },
                new TransmittedDynamicMTOfXAndYAndSubregionHistDetectorInput()
                {
                    X                   = new DoubleRange(-10.0, 10.0, 11),
                    Y                   = new DoubleRange(-10.0, 10.0, 11),
                    Z                   = new DoubleRange(0.0, 10.0, 11),
                    MTBins              = new DoubleRange(0.0, 500.0, 5),
                    FractionalMTBins    = new DoubleRange(0.0, 1.0, 11),
                    BloodVolumeFraction = new List <double>()
                    {
                        0, 0.5, 0
                    },
                }
            };

            input = new SimulationInput(
                100,
                "",
                simulationOptions,
                source,
                tissue,
                detectorsNoNASpecified);
            _outputNoNASpecified = new MonteCarloSimulation(input).Run();
        }
        public void Forecast()
        {
            var rndNumbers = new Queue <int>(new[] { 0, 2, 1, 1, 5, 3, 3, 4, 2 });
            var montecarlo = new MonteCarloSimulation(_ => rndNumbers.Dequeue());
            var sut        = new Forecasting(montecarlo, 3, 2);

            //TODO: integrationstest forecasting
            var historicalData = new[] {
                new History.Datapoint {
                    Value = 1f, Tags = new[] { "a" }
                },
                new History.Datapoint {
                    Value = 2f, Tags = new[] { "a" }
                },
                new History.Datapoint {
                    Value = 2f, Tags = new[] { "a" }
                },
                new History.Datapoint {
                    Value = 3f, Tags = new[] { "a" }
                },
                new History.Datapoint {
                    Value = 3f, Tags = new[] { "a" }
                },
                new History.Datapoint {
                    Value = 4f, Tags = new[] { "a" }
                },
                new History.Datapoint {
                    Value = 10f, Tags = new[] { "b" }
                },
                new History.Datapoint {
                    Value = 10f, Tags = new[] { "b" }
                },
                new History.Datapoint {
                    Value = 20f, Tags = new[] { "b" }
                },
                new History.Datapoint {
                    Value = 20f, Tags = new[] { "b" }
                },
                new History.Datapoint {
                    Value = 30f, Tags = new[] { "b" }
                }
            };
            var features = new[] {
                new Feature {
                    Quantity = 2, Tags = new[] { "a" }
                },
                new Feature {
                    Quantity = 1, Tags = new[] { "b" }
                },
            };

            /*
             * 3 Simulationen, 2 Intervalle
             * 2a(0..5), 1b(0..4)
             *
             * a: 0=1  1=2  3=3
             * a: 2=2  5=4  4=3
             * b: 1=10 3=20 2=20
             *    13   26   26
             *
             * 26-13=13
             * 13/2=6,5
             * 13..19,5, 19,5..26
             * (13,1,0.33), (26,2,1.0)
             */

            var result = sut.Calculate(historicalData, features);

            foreach (var f in result.Features)
            {
                Debug.WriteLine($"{string.Join(",", f)}");
            }

            foreach (var po in result.Distribution)
            {
                Debug.WriteLine($"{po.Prognosis}, {po.CummulatedProbability}");
            }

            Assert.AreEqual(new[] { "a", "a", "b" }, result.Features);
            Assert.AreEqual(2, result.Distribution.Length);
            Assert.AreEqual(3, result.Distribution.Select(g => g.Count).Sum());
            Assert.AreEqual(13f, result.Distribution[0].Prognosis);
            Assert.AreEqual(1, result.Distribution[0].Count);
            Assert.AreEqual(0.33f, result.Distribution[0].CummulatedProbability, 0.01f);
            Assert.AreEqual(26f, result.Distribution[1].Prognosis);
            Assert.AreEqual(2, result.Distribution[1].Count);
            Assert.AreEqual(1f, result.Distribution[1].CummulatedProbability, 0.01f);
        }
示例#23
0
文件: Program.cs 项目: formozov/VTS
        static void Main(string[] args)
        {
            try {
                var input = new SimulationInput(
                    1000000, // FIX 1e6 takes about 110 minutes my laptop
                    "",      // if non-empty string here, need to create sub-folder
                    new SimulationOptions(
                        0,
                        RandomNumberGeneratorType.MersenneTwister,
                        AbsorptionWeightingType.Continuous,
                        PhaseFunctionType.HenyeyGreenstein,
                        new List <DatabaseType>()
                {
                },             // databases to be written
                        false, // track statistics
                        0.0,   // RR threshold -> 0 = no RR performed
                        1),
                    new DirectionalPointSourceInput(
                        new Position(0.0, 0.0, 0.0),
                        new Direction(0.0, 0.0, 1.0),
                        0),
                    new MultiLayerTissueInput(
                        new LayerTissueRegion[]
                {
                    new LayerTissueRegion(
                        new DoubleRange(double.NegativeInfinity, 0.0),
                        new OpticalProperties(0.0, 1e-10, 0.0, 1.0)
                        ),
                    //new LayerTissueRegion(
                    //    new DoubleRange(0.0, 0.1),
                    //    new OpticalProperties(0.033, 1.0, 0.8, 1.38)
                    //    ),
                    new LayerTissueRegion(
                        new DoubleRange(0.0, 100.0),
                        new OpticalProperties(0.0, 1.0, 0.8, 1.38)
                        ),
                    new LayerTissueRegion(
                        new DoubleRange(100.0, double.PositiveInfinity),
                        new OpticalProperties(0, 1e-10, 0.0, 1.0)
                        )
                }
                        ),
                    new List <IDetectorInput>()
                {
                    new ROfRhoAndTimeDetectorInput {
                        Rho  = new DoubleRange(0.0, 40, 201),    // numbers for scaled MC
                        Time = new DoubleRange(0.0, 4, 801)
                    }                                            // numbers for scaled MC
                }
                    );

                SimulationOutput output = new MonteCarloSimulation(input).Run();
                input.ToFile("infile.txt");

                // the following gets are R(rho,time) for scaled.
                //var rOfRhoAndTime = output.ResultsDictionary[TallyType.ROfRhoAndTime.ToString()];

                //string folderPath = "results";
                //if (!Directory.Exists(folderPath))
                //    Directory.CreateDirectory(folderPath);

                //DetectorIO.WriteDetectorToFile(rOfRhoAndTime, folderPath);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to run: Reason: " + e.Message);
                throw;
                //return false;
            }
        }