示例#1
0
        public void validate_pMCROfRhoAndTimeDetector_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string         detectorName  = "testpmcrofrhoandtime";
            IDetectorInput detectorInput = new pMCROfRhoAndTimeDetectorInput()
            {
                Rho          = new DoubleRange(0, 10, 3),
                Time         = new DoubleRange(0, 1, 4),
                PerturbedOps = new List <OpticalProperties>()
                {
                    new OpticalProperties()
                },
                PerturbedRegionsIndices = new List <int>()
                {
                    1
                },
                TallySecondMoment = true, // tally SecondMoment
                Name = detectorName,
            };
            var detector = (pMCROfRhoAndTimeDetector)detectorInput.CreateDetector();

            detector.Mean = new double[, ] {
                { 1, 2, 3 }, { 4, 5, 6 }
            };
            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (pMCROfRhoAndTimeDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean[0, 0], 1);
            Assert.AreEqual(dcloned.Mean[0, 1], 2);
            Assert.AreEqual(dcloned.Mean[0, 2], 3);
            Assert.AreEqual(dcloned.Mean[1, 0], 4);
            Assert.AreEqual(dcloned.Mean[1, 1], 5);
            Assert.AreEqual(dcloned.Mean[1, 2], 6);
        }
示例#2
0
        public void validate_FluenceOfRhoAndZAndTime_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string         detectorName  = "testfluenceofrhoandzandtime";
            IDetectorInput detectorInput = new FluenceOfRhoAndZAndTimeDetectorInput()
            {
                Rho  = new DoubleRange(0, 10, 3),
                Z    = new DoubleRange(0, 10, 3),
                Time = new DoubleRange(0, 1, 4),
                TallySecondMoment = true,
                Name = detectorName,
            };
            var detector = (FluenceOfRhoAndZAndTimeDetector)detectorInput.CreateDetector();

            detector.Mean = new double[, , ] {
                { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } }
            };

            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (FluenceOfRhoAndZAndTimeDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean[0, 0, 0], 1);
            Assert.AreEqual(dcloned.Mean[0, 0, 1], 2);
            Assert.AreEqual(dcloned.Mean[0, 0, 2], 3);
            Assert.AreEqual(dcloned.Mean[0, 1, 0], 4);
            Assert.AreEqual(dcloned.Mean[0, 1, 1], 5);
            Assert.AreEqual(dcloned.Mean[0, 1, 2], 6);
            Assert.AreEqual(dcloned.Mean[1, 0, 0], 7);
            Assert.AreEqual(dcloned.Mean[1, 0, 1], 8);
            Assert.AreEqual(dcloned.Mean[1, 0, 2], 9);
            Assert.AreEqual(dcloned.Mean[1, 1, 0], 10);
            Assert.AreEqual(dcloned.Mean[1, 1, 1], 11);
            Assert.AreEqual(dcloned.Mean[1, 1, 2], 12);
        }
示例#3
0
        public void validate_AOfRhoAndZDetector_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string         detectorName  = "testaofrhoandz";
            IDetectorInput detectorInput = new AOfRhoAndZDetectorInput()
            {
                Rho = new DoubleRange(0, 10, 3),
                Z   = new DoubleRange(0, 1, 4),
                TallySecondMoment = false,
                Name = detectorName,
            };
            var detector = (AOfRhoAndZDetector)detectorInput.CreateDetector();

            detector.Mean = new double[, ] {
                { 1, 2, 3 }, { 4, 5, 6 }
            };

            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (AOfRhoAndZDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean[0, 0], 1);
            Assert.AreEqual(dcloned.Mean[0, 1], 2);
            Assert.AreEqual(dcloned.Mean[0, 2], 3);
            Assert.AreEqual(dcloned.Mean[1, 0], 4);
            Assert.AreEqual(dcloned.Mean[1, 1], 5);
            Assert.AreEqual(dcloned.Mean[1, 2], 6);
        }
示例#4
0
        public void validate_pMCROfRhoDetector_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string         detectorName  = "testpmcrofrho";
            IDetectorInput detectorInput = new pMCROfRhoDetectorInput()
            {
                Rho          = new DoubleRange(0, 10, 4),
                PerturbedOps = new List <OpticalProperties>()
                {
                    new OpticalProperties()
                },
                PerturbedRegionsIndices = new List <int>()
                {
                    1
                },
                TallySecondMoment = true, // tally SecondMoment
                Name = detectorName,
            };
            var detector = (pMCROfRhoDetector)detectorInput.CreateDetector();

            detector.Mean         = new double[] { 100, 200, 300 };
            detector.SecondMoment = new double[] { 50, 150, 250 };
            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (pMCROfRhoDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            // ckh: not sure how I would read in 2nd moment data in detector + "_2"

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean[0], 100);
            Assert.AreEqual(dcloned.Mean[1], 200);
            Assert.AreEqual(dcloned.Mean[2], 300);
        }
示例#5
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);
            }
        }
示例#6
0
        public void validate_TDiffuseDetector_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string         detectorName  = "testtdiffuse";
            IDetectorInput detectorInput = new TDiffuseDetectorInput()
            {
                TallySecondMoment = false, Name = detectorName
            };
            var detector = (TDiffuseDetector)detectorInput.CreateDetector();

            detector.Mean = 100;
            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (TDiffuseDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean, 100);
        }
示例#7
0
        public void validate_ROfRhoDetector_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string         detectorName  = "testrofrho";
            IDetectorInput detectorInput = new ROfRhoDetectorInput()
            {
                Rho = new DoubleRange(0, 10, 4), TallySecondMoment = false, Name = detectorName
            };
            var detector = (ROfRhoDetector)detectorInput.CreateDetector();

            detector.Mean = new double[] { 100, 200, 300 };
            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (ROfRhoDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean[0], 100);
            Assert.AreEqual(dcloned.Mean[1], 200);
            Assert.AreEqual(dcloned.Mean[2], 300);
        }
示例#8
0
        public void validate_RDiffuseDetector_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string         detectorName  = "testrdiffuse";
            IDetectorInput detectorInput = new RDiffuseDetectorInput()
            {
                TallySecondMoment = true, Name = detectorName
            };
            var detector = (RDiffuseDetector)detectorInput.CreateDetector();

            detector.Mean         = 100;
            detector.SecondMoment = 50;
            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (RDiffuseDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean, 100);
            Assert.AreEqual(dcloned.SecondMoment, 50); // 0D detectors 2nd moment written to .txt file
        }
示例#9
0
        public void validate_ROfRhoAndOmegaDetector_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string         detectorName  = "testrofrhoandomega";
            IDetectorInput detectorInput = new ROfRhoAndOmegaDetectorInput()
            {
                Rho               = new DoubleRange(0, 10, 3),
                Omega             = new DoubleRange(0, 1, 4),
                TallySecondMoment = true, // tally Second Moment
                Name              = detectorName,
            };
            var detector = (ROfRhoAndOmegaDetector)detectorInput.CreateDetector();

            detector.Mean = new Complex[, ]
            {
                {
                    1 + Complex.ImaginaryOne * 1, 2 + Complex.ImaginaryOne * 2, 3 + Complex.ImaginaryOne * 3,
                    4 + Complex.ImaginaryOne * 4
                },
                {
                    5 + Complex.ImaginaryOne * 5, 6 + Complex.ImaginaryOne * 6, 7 + Complex.ImaginaryOne * 7,
                    8 + Complex.ImaginaryOne * 8
                }
            };
            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (ROfRhoAndOmegaDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean[0, 0], 1 + Complex.ImaginaryOne * 1);
            Assert.AreEqual(dcloned.Mean[0, 1], 2 + Complex.ImaginaryOne * 2);
            Assert.AreEqual(dcloned.Mean[0, 2], 3 + Complex.ImaginaryOne * 3);
            Assert.AreEqual(dcloned.Mean[0, 3], 4 + Complex.ImaginaryOne * 4);
            Assert.AreEqual(dcloned.Mean[1, 0], 5 + Complex.ImaginaryOne * 5);
            Assert.AreEqual(dcloned.Mean[1, 1], 6 + Complex.ImaginaryOne * 6);
            Assert.AreEqual(dcloned.Mean[1, 2], 7 + Complex.ImaginaryOne * 7);
            Assert.AreEqual(dcloned.Mean[1, 3], 8 + Complex.ImaginaryOne * 8);
        }
示例#10
0
        public void demonstrate_user_defined_detector_usage()
        {
            DetectorFactory.RegisterDetector(typeof(ROfXDetectorInput), typeof(ROfXDetector));

            var detectorInput = new ROfXDetectorInput
            {
                TallyType         = "ROfX",
                Name              = "My First R(x) Detector",
                TallySecondMoment = true,
                X = new DoubleRange(0, 10, 101),
            };

            var simInput = new SimulationInput
            {
                DetectorInputs = new[] { detectorInput },
                N = 100,
            };

            var sim = simInput.CreateSimulation();

            var results = sim.Run();

            IDetector detector;

            var detectorExists = results.ResultsDictionary.TryGetValue(detectorInput.Name, out detector);

            Assert.IsTrue(detectorExists);

            var firstValue = ((ROfXDetector)detector).Mean.FirstOrDefault();

            Assert.IsTrue(firstValue != 0);

            DetectorIO.WriteDetectorToFile(detector, "user_defined_detector");

            var deserializedDetector = DetectorIO.ReadDetectorFromFile("user_defined_detector", "");
        }
示例#11
0
        public void setup()
        {
            // set up MC simulation that generated the absorbed energy detector results in embedded resources
            //var input = new SimulationInput(
            //100,
            //"test",
            //new SimulationOptions(
            //    0, // random number generator seed, -1=random seed, 0=fixed seed
            //    RandomNumberGeneratorType.MersenneTwister,
            //    AbsorptionWeightingType.Discrete,
            //    PhaseFunctionType.HenyeyGreenstein,
            //    new List<DatabaseType>() { }, // databases to be written
            //    false, // track statistics
            //    0.0, // RR threshold -> no RR performed
            //    0),
            //    new DirectionalPointSourceInput(
            //        new Position(0.0, 0.0, 0.0),
            //        new Direction(0.0, 0.0, 1.0),
            //        0), // 0=start in air, 1=start in tissue
            //    new SingleInfiniteCylinderTissueInput(
            //        new InfiniteCylinderTissueRegion(
            //            new Position(0, 0, 1),
            //            1.0,
            //            new OpticalProperties(0.05, 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))
            //        }
            //    ),
            //    new List<IDetectorInput>()
            //    {
            //        new AOfXAndYAndZDetectorInput(){
            //            X =new DoubleRange(-2, 2, 5),
            //            Y =new DoubleRange(-10, 10, 2),
            //            Z =new DoubleRange(0, 3, 4)}
            //    }
            //);
            //var output = new MonteCarloSimulation(input).Run();  //NOTE: this puts output in Vts.MCCL/bin/Debug
            var name         = Assembly.GetExecutingAssembly().FullName;
            var assemblyName = new AssemblyName(name).Name;

            _aOfXAndYAndZDetector = (dynamic)DetectorIO.ReadDetectorFromFileInResources(
                "AOfXAndYAndZ", "Resources/sourcetest/", assemblyName);
            // overwrite statistical data in Mean with deterministic values to test
            int count = 1;

            for (int i = 0; i < _aOfXAndYAndZDetector.X.Count - 1; i++)
            {
                for (int j = 0; j < _aOfXAndYAndZDetector.Y.Count - 1; j++)
                {
                    for (int k = 0; k < _aOfXAndYAndZDetector.Z.Count - 1; k++)
                    {
                        _aOfXAndYAndZDetector.Mean[i, j, k] = count; // make all nonzero and unique
                        ++count;
                    }
                }
            }
            DetectorIO.WriteDetectorToFile(_aOfXAndYAndZDetector, "sourcetest");

            FileIO.CopyFileFromResources(
                "Resources/sourcetest/input.txt", "sourcetest/input.txt", assemblyName);
            // following setup is used to test FluorescenceEmissionSource
            _fluorescenceEmissionAOfXAndYAndZSource = new FluorescenceEmissionAOfXAndYAndZSource(
                "sourcetest", "input.txt", 3);
            // empty infileFolder will initialize AOfXAndYAndZLoader with no AOfXAndYAndZ read
            _fluorescenceEmissionAOfXAndYAndZSource.Loader = new AOfXAndYAndZLoader(
                "sourcetest", "input.txt", 3);
            _loader = _fluorescenceEmissionAOfXAndYAndZSource.Loader;

            _loader.InitializeFluorescentRegionArrays();
        }
        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);
        }
示例#13
0
        public void validate_ReflectedMTOfRhoAndSubregionHistDetector_deserialized_class_is_correct_when_using_WriteReadDetectorToFile()
        {
            string detectorName = "testreflectedmtofrhoandsubregionhist";
            var    tissue       = new MultiLayerTissue(
                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.7, 1.33)),
                new LayerTissueRegion(
                    new DoubleRange(100.0, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            }
                );
            IDetectorInput detectorInput = new ReflectedMTOfRhoAndSubregionHistDetectorInput()
            {
                Rho               = new DoubleRange(0, 10, 3),
                MTBins            = new DoubleRange(0, 10, 3),
                FractionalMTBins  = new DoubleRange(0, 1, 2),
                TallySecondMoment = true, // tally SecondMoment
                Name              = detectorName,
            };
            var detector = (ReflectedMTOfRhoAndSubregionHistDetector)detectorInput.CreateDetector();

            // need to initialize detector so that NumSubregions gets set
            detector.Initialize(tissue, null);
            // Mean has dimensions [Rho.Count - 1, MTBins.Count - 1]
            detector.Mean = new double[, ] {
                { 1, 2 }, { 3, 4 }
            };
            // FractionalMT has dimensions [Rho.Count - 1, MTBins.Count - 1, NumSubregions, FractionalMTBins.Count + 1]=[2,2,3,3]
            detector.FractionalMT = new double[, , , ] {
                { { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }, { { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 } } }, { { { 19, 20, 21 }, { 22, 23, 24 }, { 25, 26, 27 } }, { { 28, 29, 30 }, { 31, 32, 33 }, { 34, 35, 36 } } }
            };

            DetectorIO.WriteDetectorToFile(detector, "");
            var dcloned = (ReflectedMTOfRhoAndSubregionHistDetector)DetectorIO.ReadDetectorFromFile(detectorName, "");

            Assert.AreEqual(dcloned.Name, detectorName);
            Assert.AreEqual(dcloned.Mean[0, 0], 1);
            Assert.AreEqual(dcloned.Mean[0, 1], 2);
            Assert.AreEqual(dcloned.Mean[1, 0], 3);
            Assert.AreEqual(dcloned.Mean[1, 1], 4);

            Assert.AreEqual(dcloned.FractionalMT[0, 0, 0, 0], 1);
            Assert.AreEqual(dcloned.FractionalMT[0, 0, 0, 1], 2);
            Assert.AreEqual(dcloned.FractionalMT[0, 0, 0, 2], 3);
            Assert.AreEqual(dcloned.FractionalMT[0, 0, 1, 0], 4);
            Assert.AreEqual(dcloned.FractionalMT[0, 0, 1, 1], 5);
            Assert.AreEqual(dcloned.FractionalMT[0, 0, 1, 2], 6);
            Assert.AreEqual(dcloned.FractionalMT[0, 0, 2, 0], 7);
            Assert.AreEqual(dcloned.FractionalMT[0, 0, 2, 1], 8);
            Assert.AreEqual(dcloned.FractionalMT[0, 0, 2, 2], 9);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 0, 0], 10);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 0, 1], 11);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 0, 2], 12);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 1, 0], 13);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 1, 1], 14);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 1, 2], 15);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 2, 0], 16);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 2, 1], 17);
            Assert.AreEqual(dcloned.FractionalMT[0, 1, 2, 2], 18);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 0, 0], 19);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 0, 1], 20);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 0, 2], 21);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 1, 0], 22);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 1, 1], 23);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 1, 2], 24);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 2, 0], 25);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 2, 1], 26);
            Assert.AreEqual(dcloned.FractionalMT[1, 0, 2, 2], 27);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 0, 0], 28);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 0, 1], 29);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 0, 2], 30);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 1, 0], 31);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 1, 1], 32);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 1, 2], 33);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 2, 0], 34);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 2, 1], 35);
            Assert.AreEqual(dcloned.FractionalMT[1, 1, 2, 2], 36);
        }
        public void setup()
        {
            var name         = Assembly.GetExecutingAssembly().FullName;
            var assemblyName = new AssemblyName(name).Name;

            // AOfXAndYAndZ in resource is defined by:
            // single layer tissue with embedded infinite cylinder center=(0,0,1) radius=1
            // detector x=[-2 2] 4 bins, y=[-10 10] 1 bin, z=[0 3] 3 bins
            _aOfXAndYAndZDetector = (dynamic)DetectorIO.ReadDetectorFromFileInResources(
                "AOfXAndYAndZ", "Resources/sourcetest/", assemblyName);
            // overwrite statistical data in Mean with deterministic values to test
            int count = 1;

            for (int i = 0; i < _aOfXAndYAndZDetector.X.Count - 1; i++)
            {
                for (int j = 0; j < _aOfXAndYAndZDetector.Y.Count - 1; j++)
                {
                    for (int k = 0; k < _aOfXAndYAndZDetector.Z.Count - 1; k++)
                    {
                        _aOfXAndYAndZDetector.Mean[i, j, k] = count; // make all nonzero and unique
                        ++count;
                    }
                }
            }
            DetectorIO.WriteDetectorToFile(_aOfXAndYAndZDetector, "sourcetest");

            FileIO.CopyFileFromResources(
                "Resources/sourcetest/inputAOfXAndYAndZ.txt", "sourcetest/inputAOfXAndYAndZ.txt", assemblyName);

            // following setup is used to test FluorescenceEmissionSource CDF sampling method
            _fluorEmissionAOfXAndYAndZSourceCDF = new FluorescenceEmissionAOfXAndYAndZSource(
                "sourcetest", "inputAOfXAndYAndZ.txt", 3, SourcePositionSamplingType.CDF);
            // empty infileFolder will initialize AOfXAndYAndZLoader with no AOfXAndYAndZ read
            _fluorEmissionAOfXAndYAndZSourceCDF.Loader = new AOfXAndYAndZLoader(
                "sourcetest", "inputAOfXAndYAndZ.txt", 3);
            _xyzLoaderCDF = _fluorEmissionAOfXAndYAndZSourceCDF.Loader;
            _xyzLoaderCDF.InitializeFluorescentRegionArrays();

            // following setup is used to test FluorescenceEmissionSource Unif sampling method
            _fluorEmissionAOfXAndYAndZSourceUnif = new FluorescenceEmissionAOfXAndYAndZSource(
                "sourcetest", "inputAOfXAndYAndZ.txt", 3, SourcePositionSamplingType.Uniform);
            // empty infileFolder will initialize AOfXAndYAndZLoader with no AOfXAndYAndZ read
            _fluorEmissionAOfXAndYAndZSourceUnif.Loader = new AOfXAndYAndZLoader(
                "sourcetest", "inputAOfXAndYAndZ.txt", 3);
            _xyzLoaderUnif = _fluorEmissionAOfXAndYAndZSourceCDF.Loader;

            _xyzLoaderCDF.InitializeFluorescentRegionArrays();

            // AOfRhoAndZ in resource is defined by:
            // single layer tissue with embedded infinite cylinder center=(0,0,1) radius=4
            // detector rho=[0 4] 4 bins, z=[0 2] 2 bins
            _aOfRhoAndZDetector = (dynamic)DetectorIO.ReadDetectorFromFileInResources(
                "AOfRhoAndZ", "Resources/sourcetest/", assemblyName);
            // overwrite statistical data in Mean with deterministic values to test
            count = 1;
            for (int i = 0; i < _aOfRhoAndZDetector.Rho.Count - 1; i++)
            {
                for (int k = 0; k < _aOfRhoAndZDetector.Z.Count - 1; k++)
                {
                    _aOfRhoAndZDetector.Mean[i, k] = count; // make all nonzero and unique
                    ++count;
                }
            }
            DetectorIO.WriteDetectorToFile(_aOfRhoAndZDetector, "sourcetest");

            FileIO.CopyFileFromResources(
                "Resources/sourcetest/inputAOfRhoAndZ.txt", "sourcetest/inputAOfRhoAndZ.txt", assemblyName);

            // following setup is used to test FluorescenceEmissionSource CDF sampling method
            _fluorEmissionAOfRhoAndZSourceCDF = new FluorescenceEmissionAOfRhoAndZSource(
                "sourcetest", "inputAOfRhoAndZ.txt", 3, SourcePositionSamplingType.CDF);
            // empty infileFolder will initialize AOfRhoAndZLoader with no AOfRhoAndZ read
            _fluorEmissionAOfRhoAndZSourceCDF.Loader = new AOfRhoAndZLoader(
                "sourcetest", "inputAOfRhoAndZ.txt", 3);
            _rhozLoaderCDF = _fluorEmissionAOfRhoAndZSourceCDF.Loader;
            _rhozLoaderCDF.InitializeFluorescentRegionArrays();

            // following setup is used to test FluorescenceEmissionSource Unif sampling method
            _fluorEmissionAOfRhoAndZSourceUnif = new FluorescenceEmissionAOfRhoAndZSource(
                "sourcetest", "inputAOfRhoAndZ.txt", 3, SourcePositionSamplingType.Uniform);
            // empty infileFolder will initialize AOfRhoAndZLoader with no AOfRhoAndZ read
            _fluorEmissionAOfRhoAndZSourceUnif.Loader = new AOfRhoAndZLoader(
                "sourcetest", "inputAOfRhoAndZ.txt", 3);
            _rhozLoaderUnif = _fluorEmissionAOfRhoAndZSourceCDF.Loader;

            _rhozLoaderCDF.InitializeFluorescentRegionArrays();
        }
示例#15
0
        // need to work on following
        /// <summary>
        /// Runs the Monte Carlo Post-processor
        /// </summary>
        public static void RunPostProcessor(PostProcessorInput input, string outputFolderPath)
        {
            // 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);
            }

            SimulationOutput postProcessedOutput = null;

            var databaseGenerationInputFile = SimulationInput.FromFile(Path.Combine(input.InputFolder, input.DatabaseSimulationInputFilename + ".txt"));

            // check for pMC tallies first because could have ReflectanceTallies mixed in and want to load CollisionInfo

            // Why not mirror the "on-the-fly" code, and allow for all kinds of detector inputs simultaneously? (dc 12/21/2011)
            if (input.DetectorInputs.Where(di => di.TallyDetails.IspMCReflectanceTally).Any())
            {
                IList <IDetectorInput> pMCDetectorInputs;
                pMCDetectorInputs = input.DetectorInputs;
                var postProcessor = new PhotonDatabasePostProcessor(
                    VirtualBoundaryType.pMCDiffuseReflectance,
                    pMCDetectorInputs,
                    PhotonDatabaseFactory.GetpMCDatabase( // database filenames are assumed to be convention
                        VirtualBoundaryType.pMCDiffuseReflectance,
                        input.InputFolder),
                    databaseGenerationInputFile
                    );
                postProcessedOutput = postProcessor.Run();
            }
            else if (input.DetectorInputs.Where(di => di.TallyDetails.IsReflectanceTally).Any())
            {
                var postProcessor = new PhotonDatabasePostProcessor(
                    VirtualBoundaryType.DiffuseReflectance,
                    input.DetectorInputs,
                    PhotonDatabaseFactory.GetPhotonDatabase( //database filenames are assumed to be convention
                        VirtualBoundaryType.DiffuseReflectance,
                        input.InputFolder),
                    databaseGenerationInputFile
                    );
                postProcessedOutput = postProcessor.Run();
            }
            else if (input.DetectorInputs.Where(di => di.TallyDetails.IsTransmittanceTally).Any())
            {
                var postProcessor = new PhotonDatabasePostProcessor(
                    VirtualBoundaryType.DiffuseTransmittance,
                    input.DetectorInputs,
                    PhotonDatabaseFactory.GetPhotonDatabase( //database filenames are assumed to be convention
                        VirtualBoundaryType.DiffuseTransmittance,
                        input.InputFolder),
                    databaseGenerationInputFile
                    );
                postProcessedOutput = postProcessor.Run();
            }
            else if (input.DetectorInputs.Where(di => di.TallyDetails.IsSpecularReflectanceTally).Any())
            {
                var postProcessor = new PhotonDatabasePostProcessor(
                    VirtualBoundaryType.SpecularReflectance,
                    input.DetectorInputs,
                    PhotonDatabaseFactory.GetPhotonDatabase( //database filenames are assumed to be convention
                        VirtualBoundaryType.SpecularReflectance,
                        input.InputFolder),
                    databaseGenerationInputFile
                    );
                postProcessedOutput = postProcessor.Run();
            }


            var folderPath = input.OutputName;

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

            // save input file to output folder with results
            input.ToFile(Path.Combine(resultsFolder, input.OutputName + ".txt"));

            // save database generation input file to output folder
            databaseGenerationInputFile.ToFile(Path.Combine(resultsFolder, input.OutputName + "_database_infile.txt"));

            if (postProcessedOutput != null)
            {
                foreach (var result in postProcessedOutput.ResultsDictionary.Values)
                {
                    // save all detector data to the specified folder
                    DetectorIO.WriteDetectorToFile(result, folderPath);
                }
            }
        }