Esempio n. 1
0
        private void exportSimulationToFile(Simulation simulation, string moBiFile)
        {
            _lazyLoadTask.Load(simulation);
            if (simulation.IsImported)
            {
                throw new PKSimException(PKSimConstants.Error.CannotExportAnImportedSimulation);
            }

            var configuration  = _buildConfigurationTask.CreateFor(simulation, shouldValidate: true, createAgingDataInSimulation: false);
            var moBiSimulation = _simulationMapper.MapFrom(simulation, configuration, shouldCloneModel: false);

            updateObserverForAllFlag(moBiSimulation);
            updateRepresentationInfo(moBiSimulation);
            updateFormulaIdIn(moBiSimulation);

            var simulationTransfer = new SimulationTransfer
            {
                Simulation  = moBiSimulation,
                JournalPath = _journalRetriever.JournalFullPath
            };

            var currentProject = _projectRetriever.CurrentProject;

            if (currentProject != null)
            {
                simulationTransfer.AllObservedData = simulation.UsedObservedData.Select(o => currentProject.ObservedDataBy(o.Id)).ToList();
                simulationTransfer.Favorites       = currentProject.Favorites;
            }

            _simulationPersistor.Save(simulationTransfer, moBiFile);
        }
Esempio n. 2
0
        private void exportToDirectory(ISimulation simulation, string exportDirectory)
        {
            var fileName            = createFilePathFor(simulation, exportDirectory, Constants.Filter.XML_EXTENSION);
            var modelCoreSimulation = _simulationToModelCoreSimulationMapper.MapFrom(simulation, shouldCloneModel: false);

            _simModelExporter.ExportSimModelXml(modelCoreSimulation, fileName);
        }
        private Task runSimulation(IndividualSimulation simulation, bool exportAll, bool raiseEvents, bool checkForNegativeValues)
        {
            //Should be done outside of the Task.Run to ensure that any event that might be raised by this action won't cause threading issue
            updatePersistableFor(simulation, exportAll);

            return(Task.Run(() =>
            {
                var modelCoreSimulation = _modelCoreSimulationMapper.MapFrom(simulation, shouldCloneModel: false);
                var simRunOptions = new SimulationRunOptions
                {
                    SimModelExportMode = SimModelExportMode.Optimized,
                    CheckForNegativeValues = checkForNegativeValues
                };

                var simResults = _simModelManager.RunSimulation(modelCoreSimulation, simRunOptions);

                if (!simResults.Success)
                {
                    return;
                }

                _simulationResultsSynchronizer.Synchronize(simulation, simResults.Results);
                simulation.ClearPKCache();

                if (raiseEvents)
                {
                    _eventPublisher.PublishEvent(new SimulationResultsUpdatedEvent(simulation));
                }
            }));
        }
Esempio n. 4
0
        private ISimModelBatch createSimModelBatch(ISimulation simulation)
        {
            var simModelBatch       = _simModelBatchFactory.Create();
            var modelCoreSimulation = _modelCoreSimulationMapper.MapFrom(simulation, shouldCloneModel: true);

            _timeGridUpdater.UpdateSimulationTimeGrid(modelCoreSimulation, _parameterIdentification.Configuration.RemoveLLOQMode, _parameterIdentification.AllDataRepositoryMappedFor(simulation));
            _outputSelectionUpdater.UpdateOutputsIn(modelCoreSimulation, _parameterIdentification.AllOutputsMappedFor(simulation));
            simModelBatch.InitializeWith(modelCoreSimulation, _parameterIdentification.PathOfOptimizedParameterBelongingTo(simulation), simulationResultsName: Captions.ParameterIdentification.SimulationResultsForRun(RunResult.Index));
            return(simModelBatch);
        }
Esempio n. 5
0
        protected override void Context()
        {
            _eventPublisher = A.Fake <IEventPublisher>();
            _sensitivityAnalysisVariationDataCreator = A.Fake <ISensitivityAnalysisVariationDataCreator>();
            _populationRunner             = A.Fake <IPopulationRunner>();
            _modelCoreSimulationMapper    = A.Fake <ISimulationToModelCoreSimulationMapper>();
            _runResultCalculator          = A.Fake <ISensitivityAnalysisRunResultCalculator>();
            _simulationPersistableUpdater = A.Fake <ISimulationPersistableUpdater>();
            sut = new SensitivityAnalysisEngine(_eventPublisher, _sensitivityAnalysisVariationDataCreator, _populationRunner, _modelCoreSimulationMapper, _runResultCalculator, _simulationPersistableUpdater);

            _sensitivityAnalysis = A.Fake <SensitivityAnalysis>();
            _modelCoreSimulation = A.Fake <IModelCoreSimulation>();
            A.CallTo(() => _modelCoreSimulationMapper.MapFrom(_sensitivityAnalysis.Simulation, true)).Returns(_modelCoreSimulation);
        }
        private Task runSimulation(IndividualSimulation simulation, SimulationRunOptions simulationRunOptions)
        {
            return(Task.Run(() =>
            {
                var modelCoreSimulation = _modelCoreSimulationMapper.MapFrom(simulation, shouldCloneModel: false);
                var simResults = _simModelManager.RunSimulation(modelCoreSimulation, simulationRunOptions);

                if (!simResults.Success)
                {
                    return;
                }

                _simulationResultsSynchronizer.Synchronize(simulation, simResults.Results);
                updateResultsName(simulation);

                simulation.ClearPKCache();

                raiseEvent(new SimulationResultsUpdatedEvent(simulation));
            }));
        }
        public async Task <PopulationRunResults> RunAsync(PopulationSimulation populationSimulation, SimulationRunOptions simulationRunOptions)
        {
            _progressUpdater = _progressManager.Create();
            _progressUpdater.Initialize(populationSimulation.NumberOfItems, PKSimConstants.UI.Calculating);

            var begin = SystemTime.UtcNow();

            try
            {
                var populationData      = _populationExporter.CreatePopulationDataFor(populationSimulation);
                var modelCoreSimulation = _modelCoreSimulationMapper.MapFrom(populationSimulation, shouldCloneModel: false);
                var runOptions          = new RunOptions {
                    NumberOfCoresToUse = _userSettings.MaximumNumberOfCoresToUse
                };
                _eventPublisher.PublishEvent(new SimulationRunStartedEvent());
                var populationRunResults = await _populationRunner.RunPopulationAsync(modelCoreSimulation, runOptions, populationData, populationSimulation.AgingData.ToDataTable());

                _simulationResultsSynchronizer.Synchronize(populationSimulation, populationRunResults.Results);
                _populationSimulationAnalysisSynchronizer.UpdateAnalysesDefinedIn(populationSimulation);
                _eventPublisher.PublishEvent(new SimulationResultsUpdatedEvent(populationSimulation));

                return(populationRunResults);
            }
            catch (OperationCanceledException)
            {
                simulationTerminated();
                return(null);
            }
            catch (Exception)
            {
                simulationTerminated();
                throw;
            }
            finally
            {
                var end       = SystemTime.UtcNow();
                var timeSpent = end - begin;
                _eventPublisher.PublishEvent(new SimulationRunFinishedEvent(populationSimulation, timeSpent));
            }
        }
        public async Task RunAsync(PopulationSimulation populationSimulation)
        {
            _progressUpdater = _progressManager.Create();
            _progressUpdater.Initialize(populationSimulation.NumberOfItems, PKSimConstants.UI.Calculating);
            _populationRunner.NumberOfCoresToUse = _userSettings.MaximumNumberOfCoresToUse;

            //make sure that thread methods always catch and handle any exception,
            //otherwise we risk unplanned application termination
            var begin = SystemTime.UtcNow();

            try
            {
                var populationData      = _populationExporter.CreatePopulationDataFor(populationSimulation);
                var modelCoreSimulation = _modelCoreSimulationMapper.MapFrom(populationSimulation, shouldCloneModel: false);
                _simulationPersistableUpdater.UpdatePersistableFromSettings(populationSimulation);

                _eventPublisher.PublishEvent(new SimulationRunStartedEvent());
                var populationRunResults = await _populationRunner.RunPopulationAsync(modelCoreSimulation, populationData, populationSimulation.AgingData.ToDataTable());

                _simulationResultsSynchronizer.Synchronize(populationSimulation, populationRunResults.Results);
                _populationSimulationAnalysisSynchronizer.UpdateAnalysesDefinedIn(populationSimulation);
                _eventPublisher.PublishEvent(new SimulationResultsUpdatedEvent(populationSimulation));
            }
            catch (OperationCanceledException)
            {
                simulationTerminated();
            }
            catch (Exception ex)
            {
                _exceptionManager.LogException(ex);
                simulationTerminated();
            }
            finally
            {
                var end       = SystemTime.UtcNow();
                var timeSpent = end - begin;
                _eventPublisher.PublishEvent(new SimulationRunFinishedEvent(populationSimulation, timeSpent));
            }
        }
        public async Task StartAsync(SensitivityAnalysis sensitivityAnalysis, SensitivityAnalysisRunOptions runOptions)
        {
            _sensitivityAnalysis = sensitivityAnalysis;
            _eventPublisher.PublishEvent(new SensitivityAnalysisStartedEvent(sensitivityAnalysis));

            try
            {
                var modelCoreSimulation = _modelCoreSimulationMapper.MapFrom(sensitivityAnalysis.Simulation, shouldCloneModel: true);
                _simulationPersistableUpdater.UpdateSimulationPersistable(modelCoreSimulation);
                var variationData = _sensitivityAnalysisVariationDataCreator.CreateForRun(sensitivityAnalysis);
                var runResults    = await _populationRunner.RunPopulationAsync(modelCoreSimulation, runOptions, variationData.ToDataTable());

                sensitivityAnalysis.Results = await calculateSensitivityBasedOn(sensitivityAnalysis, variationData, runResults, runOptions);

                _eventPublisher.PublishEvent(new SensitivityAnalysisResultsUpdatedEvent(sensitivityAnalysis));
            }
            finally
            {
                _eventPublisher.PublishEvent(new SensitivityAnalysisTerminatedEvent(sensitivityAnalysis));
                _sensitivityAnalysis = null;
            }
        }
        protected override void Context()
        {
            _modelCoreSimulationMapper   = A.Fake <ISimulationToModelCoreSimulationMapper>();
            _residualCalculatorFactory   = A.Fake <IResidualCalculatorFactory>();
            _timeGridUpdater             = A.Fake <ITimeGridUpdater>();
            _simModelBatchFactory        = A.Fake <ISimModelBatchFactory>();
            _optimizationAlgorithmMapper = A.Fake <IParameterIdentificationAlgorithmToOptmizationAlgorithmMapper>();
            _outputSelectionUpdater      = A.Fake <IOutputSelectionUpdater>();
            _coreUserSettings            = A.Fake <ICoreUserSettings>();
            _jacobianMatrixCalculator    = A.Fake <IJacobianMatrixCalculator>();

            _coreUserSettings.MaximumNumberOfCoresToUse = 2;
            sut = new ParameterIdentificationRun(_residualCalculatorFactory, _timeGridUpdater, _simModelBatchFactory, _modelCoreSimulationMapper,
                                                 _optimizationAlgorithmMapper, _outputSelectionUpdater, _coreUserSettings, _jacobianMatrixCalculator);

            _simulation           = A.Fake <ISimulation>();
            _parameter1           = A.Fake <IParameter>();
            _parameter1.Dimension = DomainHelperForSpecs.ConcentrationDimensionForSpecs();
            _parameter1.Value     = 15;
            _parameter2           = A.Fake <IParameter>();
            _parameter2.Value     = 35;
            _parameter2.Dimension = DomainHelperForSpecs.ConcentrationDimensionForSpecs();

            _parameterIdentification = new ParameterIdentification();
            _parameterIdentification.Configuration.LLOQMode       = LLOQModes.OnlyObservedData;
            _parameterIdentification.Configuration.RemoveLLOQMode = RemoveLLOQModes.NoTrailing;

            _parameterIdentification.AddSimulation(_simulation);

            _parameterSelection1 = ParameterSelectionFor(_parameter1, "ParameterPath1");
            _parameterSelection2 = ParameterSelectionFor(_parameter2, "ParameterPath2");

            _identificationParameter = DomainHelperForSpecs.IdentificationParameter("IdParam", min: 10, max: 20, startValue: 15);

            _identificationParameter.AddLinkedParameter(_parameterSelection1);
            _identificationParameter.AddLinkedParameter(_parameterSelection2);

            _modelCoreSimulation = A.Fake <IModelCoreSimulation>();

            A.CallTo(() => _modelCoreSimulationMapper.MapFrom(_simulation, true)).Returns(_modelCoreSimulation);

            _outputMapping = A.Fake <OutputMapping>();
            A.CallTo(() => _outputMapping.UsesSimulation(_simulation)).Returns(true);
            A.CallTo(() => _outputMapping.WeightedObservedData.ObservedData).Returns(DomainHelperForSpecs.ObservedData());
            _parameterIdentification.AddOutputMapping(_outputMapping);

            _simModelBatch = A.Fake <ISimModelBatch>();
            A.CallTo(() => _simModelBatchFactory.Create()).Returns(_simModelBatch);

            _parameterIdentification.AddIdentificationParameter(_identificationParameter);

            _residualCalculator = A.Fake <IResidualCalculator>();
            A.CallTo(_residualCalculatorFactory).WithReturnType <IResidualCalculator>().Returns(_residualCalculator);

            _algorithm = A.Fake <IOptimizationAlgorithm>();
            A.CallTo(() => _optimizationAlgorithmMapper.MapFrom(_parameterIdentification.AlgorithmProperties)).Returns(_algorithm);

            _cancellationTokenSource = new CancellationTokenSource();
            _cancellationToken       = _cancellationTokenSource.Token;

            _runInitializer = A.Fake <IParameterIdentifcationRunInitializer>();
            A.CallTo(() => _runInitializer.InitializeRun()).ReturnsAsync(_parameterIdentification);

            PerformExtraInitializationSteps();
            sut.InitializeWith(_runInitializer);
        }
Esempio n. 11
0
        public void ExportForCluster(PopulationSimulation populationSimulation)
        {
            _lazyLoadTask.Load(populationSimulation);

            if (settingsRequired(populationSimulation))
            {
                var outputSelections = _simulationSettingsRetriever.SettingsFor(populationSimulation);
                if (outputSelections == null)
                {
                    return;
                }

                populationSimulation.OutputSelections.UpdatePropertiesFrom(outputSelections, _cloner);
            }

            FileSelection populationExport;

            using (var presenter = _applicationController.Start <ISelectFilePresenter>())
            {
                populationExport = presenter.SelectDirectory(PKSimConstants.UI.ExportForClusterSimulationTitle, Constants.DirectoryKey.SIM_MODEL_XML);
            }
            if (populationExport == null)
            {
                return;
            }

            var populationFolder = populationExport.FilePath;
            var existingFiles    = Directory.GetFiles(populationFolder);

            if (existingFiles.Any())
            {
                if (_dialogCreator.MessageBoxYesNo(PKSimConstants.UI.DeleteFilesIn(populationFolder)).Equals(ViewResult.No))
                {
                    return;
                }

                existingFiles.Each(FileHelper.DeleteFile);
            }

            var fileName                      = populationSimulation.Name;
            var modelFileFullPath             = Path.Combine(populationFolder, $"{fileName}.xml");
            var agingFileFullPath             = Path.Combine(populationFolder, $"{fileName}{CoreConstants.Population.TableParameterExport}.csv");
            var outputDeffinitionFileFullPath = Path.Combine(populationFolder, $"{fileName}{CoreConstants.Population.OutputDefinitionExport}.csv");

            //Model
            _simModelExporter.Export(_modelCoreSimulationMapper.MapFrom(populationSimulation, shouldCloneModel: false), modelFileFullPath);
            // Outputs

            var outputSelection = populationSimulation.OutputSelections;

            exportOutputDefiniton(outputSelection, outputDeffinitionFileFullPath);

            //all values
            var dataTable = CreatePopulationDataFor(populationSimulation);

            dataTable.ExportToCSV(Path.Combine(populationFolder, $"{fileName}.csv"), comments: getProjectMetaInfo(populationExport.Description));

            //all aging data
            var agingData = populationSimulation.AgingData.ToDataTable();

            if (agingData.Rows.Count > 0)
            {
                agingData.ExportToCSV(agingFileFullPath, comments: getProjectMetaInfo(populationExport.Description));
            }
        }
Esempio n. 12
0
 public Task ExportSimulationToSimModelXmlAsync(Simulation simulation, string fileName)
 {
     return(Task.Run(() => _simModelExporter.Export(_coreSimulationMapper.MapFrom(simulation, shouldCloneModel: false), fileName)));
 }
Esempio n. 13
0
 public Task ExportSimulationToCppAsync(Simulation simulation, string outputFolder)
 {
     _lazyLoadTask.Load(simulation);
     return(Task.Run(() => _simModelExporter.ExportCppCode(_coreSimulationMapper.MapFrom(simulation, shouldCloneModel: false), outputFolder, FormulaExportMode.Formula)));
 }