Example #1
0
        public void validate_only_one_perturbed_region_index_specified()
        {
            var tissueInput = new MultiLayerTissueInput();
            var input       = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                tissueInput,
                new List <IDetectorInput>()
            {
                new dMCdROfRhodMuaDetectorInput()
                {
                    Rho = new DoubleRange(0.0, 100.0),
                    // set perturbed ops to reference ops
                    PerturbedOps = new List <OpticalProperties>()
                    {
                        tissueInput.Regions[0].RegionOP,
                        tissueInput.Regions[1].RegionOP,
                        tissueInput.Regions[2].RegionOP
                    },
                    PerturbedRegionsIndices = new List <int>()
                    {
                        1, 2
                    }
                }
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_ellipsoid_is_within_tissue_layer()
        {
            var input = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                new SingleEllipsoidTissueInput(
                    new EllipsoidTissueRegion(new Position(0, 0, 0), 1.0, 1.0, 1.0, new OpticalProperties()),
                    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, 20.0),
                    new OpticalProperties(0.01, 1.0, 0.8, 1.4)),
                new LayerTissueRegion(
                    new DoubleRange(20.0, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            }
                    ),
                new List <IDetectorInput>()
            {
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
Example #3
0
        public void validate_voxel_refractive_index_matches_that_of_surrounding_layer()
        {
            var input = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                new SingleVoxelTissueInput(
                    new VoxelTissueRegion(new DoubleRange(-5, 5),
                                          new DoubleRange(-5, 5),
                                          new DoubleRange(1, 2),
                                          new OpticalProperties(0.01, 1.0, 0.9, 1.3)),
                    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, 20.0),
                    new OpticalProperties(0.01, 1.0, 0.8, 1.4)),
                new LayerTissueRegion(
                    new DoubleRange(20.0, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            }
                    ),
                new List <IDetectorInput>()
            {
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
Example #4
0
        public void validate_at_least_one_tissue_layer_defined()
        {
            var input = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                new SingleVoxelTissueInput(
                    new VoxelTissueRegion(),
                    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, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            }
                    ),
                new List <IDetectorInput>()
            {
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
Example #5
0
        public void validate_voxel_has_nonzero_dimensions()
        {
            var input = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                new SingleVoxelTissueInput(
                    // set ellipsoid axis to 0.0
                    new VoxelTissueRegion(new DoubleRange(0, 0),
                                          new DoubleRange(-10, 10),
                                          new DoubleRange(1, 5),
                                          new OpticalProperties()),
                    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, 20.0),
                    new OpticalProperties(0.01, 1.0, 0.8, 1.4)),
                new LayerTissueRegion(
                    new DoubleRange(20.0, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            }
                    ),
                new List <IDetectorInput>()
            {
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
Example #6
0
        public void validate_voxel_is_within_tissue_layer()
        {
            var input = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                new SingleVoxelTissueInput(
                    new VoxelTissueRegion(new DoubleRange(-5, 5),
                                          new DoubleRange(-5, 5),
                                          new DoubleRange(0, 10), // eheck that voxel not at surface
                                          new OpticalProperties()),
                    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, 20.0),
                    new OpticalProperties(0.01, 1.0, 0.8, 1.4)),
                new LayerTissueRegion(
                    new DoubleRange(20.0, double.PositiveInfinity),
                    new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
            }
                    ),
                new List <IDetectorInput>()
            {
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        private void MC_LoadSimulationInput_Executed(object sender, ExecutedEventArgs e)
        {
            using (var stream = StreamFinder.GetLocalFilestreamFromOpenFileDialog("txt"))
            {
                if (stream != null)
                {
                    var simulationInput = FileIO.ReadFromJsonStream <SimulationInput>(stream);

                    var validationResult = SimulationInputValidation.ValidateInput(simulationInput);
                    if (validationResult.IsValid)
                    {
                        _simulationInputVM.SimulationInput = simulationInput;
                        logger.Info(() => "Simulation input loaded.\r");
                    }
                    else
                    {
                        logger.Info(() => "Simulation input not loaded - JSON format not valid.\r");
                    }
                }
                else
                {
                    logger.Info(() => "JSON File not loaded.\r");
                }
            }
        }
Example #8
0
        public void validate_layers_have_ZRange_Count_set_to_2()
        {
            var input = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                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)
                {
                    Count = 10
                },
                    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))
            }
                    ),
                new List <IDetectorInput>()
            {
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
Example #9
0
        public void validate_top_and_bottom_layers_are_air()
        {
            var input = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                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 List <IDetectorInput>()
            {
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_null_detector_input_is_invalid_when_no_database_specified()
        {
            // generate input without any detector inputs and no database specified
            var input = new SimulationInput()  // default constructor has empty list of databases
            {
                DetectorInputs = new List <IDetectorInput> {
                }
            };
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_angled_source_and_cylindrical_detectors_are_not_defined_together()
        {
            // generate input with angled source and cylindrical detector
            var input = new SimulationInput()
            {
                SourceInput = new DirectionalPointSourceInput(
                    new Position(0, 0, 0), new Direction(1.0 / Math.Sqrt(2), 0, 1.0 / Math.Sqrt(2)), 1),
                DetectorInputs = new List <IDetectorInput> {
                    new ROfRhoDetectorInput()
                }
            };
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_null_detector_input_is_valid_when_database_specified()
        {
            // generate input without any detector inputs but with database specified
            var input = new SimulationInput()
            {
                DetectorInputs = new List <IDetectorInput> {
                }
            };

            input.Options.Databases = new List <DatabaseType> {
                DatabaseType.DiffuseReflectance
            };
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsTrue(result.IsValid);
        }
        public void validate_detector_input_not_implemented_is_invalid()
        {
            // generate input with detector input not implemented yet
            var input = new SimulationInput()
            {
                Options = new SimulationOptions()
                {
                    AbsorptionWeightingType = AbsorptionWeightingType.Continuous
                },
                DetectorInputs = new List <IDetectorInput> {
                    new RadianceOfXAndYAndZAndThetaAndPhiDetectorInput()
                }
            };
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_voxel_tissue_and_ROfFx_detectors_are_not_defined_together()
        {
            // generate input embedded ellipsoid tissue and cylindrical detector
            var input = new SimulationInput()
            {
                TissueInput = new SingleVoxelTissueInput()
                {
                    VoxelRegion = new VoxelTissueRegion()
                },
                DetectorInputs = new List <IDetectorInput> {
                    new ROfFxDetectorInput()
                }
            };
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_ellipsoid_tissue_with_off_zaxis_center_and_cylindrical_detectors_are_not_defined_together()
        {
            // generate input embedded ellipsoid tissue and cylindrical detector
            var input = new SimulationInput()
            {
                TissueInput = new SingleEllipsoidTissueInput()
                {
                    EllipsoidRegion = new EllipsoidTissueRegion()
                    {
                        Center = new Position(1, 1, 0)
                    }
                },
                DetectorInputs = new List <IDetectorInput> {
                    new ROfRhoDetectorInput()
                }
            };
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_ellipsoid_tissue_without_cylindrical_symmetry_and_cylindrical_detectors_are_not_defined_together()
        {
            // generate input embedded ellipsoid tissue and cylindrical detector
            var input = new SimulationInput()
            {
                TissueInput = new SingleEllipsoidTissueInput()
                {
                    EllipsoidRegion = new EllipsoidTissueRegion()
                    {
                        Dx = 1.0, Dy = 2.0
                    }
                },
                DetectorInputs = new List <IDetectorInput> {
                    new ROfRhoDetectorInput()
                }
            };
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_code_checks_that_detector_defined_on_tissue_surface()
        {
            var tissueInput = new MultiLayerTissueInput();
            var input       = new SimulationInput(
                10,
                "",
                new SimulationOptions(),
                new DirectionalPointSourceInput(),
                tissueInput,
                new List <IDetectorInput>()
            {
                new SurfaceFiberDetectorInput()
                {
                    Center = new Position(0, 0, 10)
                }
            }
                );
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        public void validate_tissue_optical_properties_are_non_negative()
        {
            // generate input embedded ellipsoid tissue and cylindrical detector
            var input = new SimulationInput()
            {
                TissueInput = 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(-1.0, 1.0, 0.8, 1.4)), // make mua negative
                    new LayerTissueRegion(
                        new DoubleRange(100.0, double.PositiveInfinity),
                        new OpticalProperties(0.0, 1e-10, 1.0, 1.0))
                })
            };
            var result = SimulationInputValidation.ValidateInput(input);

            Assert.IsFalse(result.IsValid);
        }
        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);
        }
Example #20
0
 public static ValidationResult ValidateSimulationInput(SimulationInput input)
 {
     return(SimulationInputValidation.ValidateInput(input));
 }