protected override void Context() { _projectPersistor = A.Fake <IProjectPersistor>(); _historyManagerPersistor = A.Fake <IHistoryManagerPersistor>(); _progressManager = A.Fake <IProgressManager>(); _workspaceLayoutPersistor = A.Fake <IWorkspaceLayoutPersistor>(); _historyManager = A.Fake <IHistoryManager>(); _projectFileCompressor = A.Fake <IProjectFileCompressor>(); _databaseSchemaMigrator = A.Fake <IDatabaseSchemaMigrator>(); _journalLoader = A.Fake <IJournalLoader>(); _projectClassifiableUpdaterAfterDeserialization = A.Fake <IProjectClassifiableUpdaterAfterDeserialization>(); _command1 = A.Fake <IPKSimCommand>(); _command2 = A.Fake <IPKSimCommand>(); var history1 = A.Fake <IHistoryItem>(); A.CallTo(() => history1.Command).Returns(_command1); var history2 = A.Fake <IHistoryItem>(); A.CallTo(() => history2.Command).Returns(_command2); A.CallTo(() => _progressManager.Create()).Returns(A.Fake <IProgressUpdater>()); A.CallTo(() => _historyManager.History).Returns(new[] { history1, history2 }); _workspace = A.Fake <IWorkspace>(); _workspace.HistoryManager = _historyManager; _session = A.Fake <ISession>(); _transaction = A.Fake <ITransaction>(); A.CallTo(() => _session.BeginTransaction()).Returns(_transaction); _sessionManager = A.Fake <ISessionManager>(); A.CallTo(() => _sessionManager.OpenSession()).Returns(_session); _fileName = "c:\\toto.txt"; sut = new WorkspacePersistor(_projectPersistor, _historyManagerPersistor, _workspaceLayoutPersistor, _sessionManager, _progressManager, _projectFileCompressor, _databaseSchemaMigrator, _journalLoader, _projectClassifiableUpdaterAfterDeserialization); }
public async Task RunAsync(IndividualSimulation individualSimulation) { _progressUpdater = _progressManager.Create(); _progressUpdater.Initialize(100, PKSimConstants.UI.Calculating); _simModelManager.SimulationProgress += simulationProgress; //make sure that thread methods always catch and handle any exception, //otherwise we risk unplanned application termination var begin = SystemTime.UtcNow(); try { _eventPublisher.PublishEvent(new SimulationRunStartedEvent()); await runSimulation(individualSimulation, exportAll : false, raiseEvents : true, checkForNegativeValues : true); } catch (Exception ex) { _exceptionManager.LogException(ex); terminated(); } finally { var end = SystemTime.UtcNow(); var timeSpent = end - begin; _eventPublisher.PublishEvent(new SimulationRunFinishedEvent(individualSimulation, timeSpent)); } }
public async Task <SimulationResultsImport> ImportResults(IModelCoreSimulation simulation, IReadOnlyCollection <string> files, CancellationToken cancellationToken, bool showImportProgress = true) { using (var progressUpdater = showImportProgress ? _progressManager.Create() : new NoneProgressUpdater()) { progressUpdater.Initialize(files.Count, Messages.ImportingResults); // Use ToList to execute the query and start the import task. var tasks = files.Select(f => importFiles(f, simulation, cancellationToken)).ToList(); var allImportedResults = new List <IndividualResultsImport>(); // Await the completion of all the running tasks. // Add a loop to process the tasks one at a time until none remain. while (tasks.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); // Identify the first task that completes. var firstFinishedTask = await Task.WhenAny(tasks); // Remove the selected task from the list so that you don't // process it more than once. tasks.Remove(firstFinishedTask); // Await the completed task. allImportedResults.Add(await firstFinishedTask); progressUpdater.IncrementProgress(); } //once all results have been imported, it is time to ensure that they are consistent var results = createSimulationResultsFrom(allImportedResults, simulation); addImportedQuantityToLogForSuccessfulImport(results); return(results); } }
protected override void Context() { _populationRunner = A.Fake <IPopulationRunner>(); _exceptionManager = A.Fake <IExceptionManager>(); _eventPubliser = A.Fake <IEventPublisher>(); _progressUpdater = A.Fake <IProgressUpdater>(); _progressManager = A.Fake <IProgressManager>(); _simulationResultsSynchronizer = A.Fake <ISimulationResultsSynchronizer>(); _simMapper = A.Fake <ISimulationToModelCoreSimulationMapper>(); _popExportTask = A.Fake <IPopulationExportTask>(); _simulationPersistableUpdater = A.Fake <ISimulationPersistableUpdater>(); _userSettings = A.Fake <ICoreUserSettings>(); _populationSimulationAnalysisSynchronizer = A.Fake <IPopulationSimulationAnalysisSynchronizer>(); sut = new PopulationSimulationEngine(_populationRunner, _progressManager, _eventPubliser, _exceptionManager, _simulationResultsSynchronizer, _popExportTask, _simMapper, _simulationPersistableUpdater, _userSettings, _populationSimulationAnalysisSynchronizer); A.CallTo(() => _progressManager.Create()).Returns(_progressUpdater); }
private void initializeProgress() { if (!_shouldRaiseEvents) { return; } _progressUpdater = _progressManager.Create(); _progressUpdater.Initialize(100, PKSimConstants.UI.Calculating); }
public void SaveSession(ICoreWorkspace workspace, string fileFullPath) { using (var progress = _progressManager.Create()) { progress.Initialize(5); progress.IncrementProgress(PKSimConstants.UI.CreatingProjectDatabase); _sessionManager.CreateFactoryFor(fileFullPath); using (var session = _sessionManager.OpenSession()) using (var transaction = session.BeginTransaction()) { progress.IncrementProgress(PKSimConstants.UI.SavingProject); workspace.UpdateJournalPathRelativeTo(fileFullPath); _projectPersistor.Save(workspace.Project, session); progress.IncrementProgress(PKSimConstants.UI.SavingHistory); _historyManagerPersistor.Save(workspace.HistoryManager, session); progress.IncrementProgress(PKSimConstants.UI.SavingLayout); if (workspace is IWithWorkspaceLayout withWorkspaceLayout) { _workspaceLayoutPersistor.Save(withWorkspaceLayout.WorkspaceLayout, session); } transaction.Commit(); } progress.IncrementProgress(PKSimConstants.UI.CompressionProject); _projectFileCompressor.Compress(fileFullPath); //once saved, we can _projectPersistor.UpdateProjectAfterSave(workspace.Project); } workspace.Project.Name = FileHelper.FileNameFromFileFullPath(fileFullPath); }
public async Task <SimulationResultsImport> ImportResults(PopulationSimulation populationSimulation, IReadOnlyCollection <string> files, CancellationToken cancellationToken) { try { using (var progressUpdater = _progressManager.Create()) { progressUpdater.Initialize(files.Count, PKSimConstants.UI.ImportingResults); _allQuantities = _quantitiesRetriever.QuantitiesFrom(populationSimulation); // Use ToList to execute the query and start the import task. var tasks = files.Select(f => importFiles(f, populationSimulation, cancellationToken)).ToList(); var allImportedResults = new List <IndividualResultsImport>(); // Await the completion of all the running tasks. // Add a loop to process the tasks one at a time until none remain. while (tasks.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); // Identify the first task that completes. var firstFinishedTask = await Task.WhenAny(tasks); // Remove the selected task from the list so that you don't // process it more than once. tasks.Remove(firstFinishedTask); // Await the completed task. allImportedResults.Add(await firstFinishedTask); progressUpdater.IncrementProgress(); } //once all results have been imported, it is time to ensure that they are consistent var results = createSimulationResultsFrom(allImportedResults); //last but not least, check that the number of individuals in the simulation matches the simulation results var importedCount = results.SimulationResults.Count; var expectedCount = populationSimulation.NumberOfItems; if (expectedCount != importedCount) { results.AddError(PKSimConstants.Error.NumberOfIndividualsInResultsDoNotMatchPopulation(populationSimulation.Name, expectedCount, importedCount)); } addImportedQuantityToLogForSuccessfulImport(results); return(results); } } finally { _allQuantities.Clear(); } }
protected override void Context() { _simModelManager = A.Fake <ISimModelManager>(); _progressUpdater = A.Fake <IProgressUpdater>(); _progressManager = A.Fake <IProgressManager>(); _eventPublisher = A.Fake <IEventPublisher>(); _exceptionManager = A.Fake <IExceptionManager>(); _simulationResultsSynchronizer = A.Fake <ISimulationResultsSynchronizer>(); _modelCoreSimulationMapper = A.Fake <ISimulationToModelCoreSimulationMapper>(); _simulationPersistableUpdater = A.Fake <ISimulationPersistableUpdater>(); A.CallTo(() => _progressManager.Create()).Returns(_progressUpdater); sut = new IndividualSimulationEngine(_simModelManager, _progressManager, _simulationResultsSynchronizer, _eventPublisher, _exceptionManager, _modelCoreSimulationMapper, _simulationPersistableUpdater); }
public async Task <ImportPopulation> CreateFor(IReadOnlyCollection <string> files, Individual individual, CancellationToken cancellationToken) { try { using (var progressUpdater = _progressManager.Create()) { var importPopulation = createPopulationFor(individual); var popIndiviudal = importPopulation.Settings.BaseIndividual; _allParameters = _containerTask.CacheAllChildren <IParameter>(popIndiviudal); _allCreateIndividualParameters = _containerTask.CacheAllChildrenSatisfying <IParameter>(popIndiviudal, x => x.IsChangedByCreateIndividual); var settings = importPopulation.Settings; progressUpdater.Initialize(files.Count, PKSimConstants.UI.CreatingPopulation); //Create the new task and start the import using to list var tasks = files.Select(f => importFiles(f, cancellationToken)).ToList(); // Add a loop to process the tasks one at a time until none remain. while (tasks.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); // Identify the first task that completes. var firstFinishedTask = await Task.WhenAny(tasks); // Remove the selected task from the list so that you don't // process it more than once. tasks.Remove(firstFinishedTask); // Await the completed task. var importResult = await firstFinishedTask; settings.AddFile(importResult.PopulationFile); mergeImportedIndividualsInPopulation(importPopulation, importResult.IndividualValues); progressUpdater.IncrementProgress(); } //once all individuals have been imported, we need to create advanced parameters createAdvancedParametersFor(importPopulation); return(importPopulation); } } finally { _allCreateIndividualParameters.Clear(); _allParameters.Clear(); } }
private void loadObjectBase <T>(T objectToLoad) where T : IObjectBase { using (var progressUpdater = _progressManager.Create()) { progressUpdater.ReportStatusMessage(PKSimConstants.UI.LoadingObject(objectToLoad.Name)); //first unregistered the object to load that might contain dummy objects that should be deleted _registrationTask.Unregister(objectToLoad); //load object content _contentLoader.LoadContentFor(objectToLoad); _registrationTask.Register(objectToLoad); //special loading steps for simulation loadSimulations(objectToLoad as Simulation); } }
protected override Task Context() { _simModelManager = A.Fake <ISimModelManager>(); _progressUpdater = A.Fake <IProgressUpdater>(); _progressManager = A.Fake <IProgressManager>(); _eventPublisher = A.Fake <IEventPublisher>(); _simulationResultsSynchronizer = A.Fake <ISimulationResultsSynchronizer>(); _modelCoreSimulationMapper = A.Fake <ISimulationToModelCoreSimulationMapper>(); sut = new IndividualSimulationEngine(_simModelManager, _progressManager, _simulationResultsSynchronizer, _eventPublisher, _modelCoreSimulationMapper); A.CallTo(() => _progressManager.Create()).Returns(_progressUpdater); _simulationRunOption = new SimulationRunOptions { RaiseEvents = true }; return(_completed); }
protected override void Context() { _registrationTask = A.Fake <IRegistrationTask>(); _progressManager = A.Fake <IProgressManager>(); _progressUpdater = A.Fake <IProgressUpdater>(); _contentLoader = A.Fake <IContentLoader>(); _simulationChartsLoader = A.Fake <ISimulationChartsLoader>(); _simulationResultsLoader = A.Fake <ISimulationResultsLoader>(); _simulationComparisonContentLoader = A.Fake <ISimulationComparisonContentLoader>(); _simulationAnalysesLoader = A.Fake <ISimulationAnalysesLoader>(); _parameterIdentificationContentendLoader = A.Fake <IParameterIdentificationContentLoader>(); _sensitivityAnalysisContentLoader = A.Fake <ISensitivityAnalysisContentLoader>(); A.CallTo(() => _progressManager.Create()).Returns(_progressUpdater); sut = new LazyLoadTask(_contentLoader, _simulationResultsLoader, _simulationChartsLoader, _simulationComparisonContentLoader, _simulationAnalysesLoader, _parameterIdentificationContentendLoader, _sensitivityAnalysisContentLoader, _registrationTask, _progressManager); _objectToLoad = A.Fake <IPKSimBuildingBlock>(); _objectToLoad.Id = "objectId"; }
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 Task <RandomPopulation> CreateFor(RandomPopulationSettings populationSettings, CancellationToken cancellationToken) { Task <RandomPopulation> task = Task.Run(() => { using (var progressUpdater = _progressManager.Create()) { var randomPopulation = createPopulationFor(populationSettings); fllUpGenderQueueBasedOn(populationSettings); progressUpdater.Initialize(populationSettings.NumberOfIndividuals, PKSimConstants.UI.CreatingPopulation); _randomGenerator = randomPopulation.RandomGenerator; //the base indiviudal is used to retrieve the default values. var baseIndividual = populationSettings.BaseIndividual; //current individual defined as a clone of the based individual. The current individual will be the one varying var currentIndividual = _cloner.Clone(populationSettings.BaseIndividual); //cache containing all parameters changed by the create individual from the current individual. This will be used just as reference to the current parameters var allChangedByCreatedIndividualParameters = getAllCreateIndividualParametersFrom(currentIndividual); //all distributed parameters. This will be used to udpate the distribution for the current individual var allDistributedParameters = getAllDistributedParametersFrom(currentIndividual); var allBaseDistributedParamters = getAllDistributedParametersFrom(baseIndividual); //all individual parameters. Just an optimiztion to avoid call GetAllChildren for each individual var allIndividualParameters = currentIndividual.GetAllChildren <IParameter>().ToList(); int maxTotalIterations = populationSettings.NumberOfIndividuals * _maxIterations; uint numberOfTry = 0; var currentGender = _genderQueue.Dequeue(); do { cancellationToken.ThrowIfCancellationRequested(); numberOfTry++; //could not create one item in max Iteration try=>exit if (numberOfTry > _maxIterations && randomPopulation.NumberOfItems == 0) { throw new CannotCreatePopulationWithConstraintsException(_reportGenerator.StringReportFor(populationSettings)); } //create a new individual based on population settings defined by the user updateCurrentIndividualFromSettings(populationSettings, currentIndividual, allDistributedParameters, allBaseDistributedParamters, currentGender); bool success = tryRandomize(currentIndividual, populationSettings, allIndividualParameters); if (!success) { continue; } randomPopulation.AddIndividualProperties(_individualPropertiesMapper.MapFrom(currentIndividual, allChangedByCreatedIndividualParameters)); currentGender = _genderQueue.Dequeue(); progressUpdater.IncrementProgress(PKSimConstants.UI.CreatingIndividualInPopulation(randomPopulation.NumberOfItems, populationSettings.NumberOfIndividuals)); } while (randomPopulation.NumberOfItems < populationSettings.NumberOfIndividuals && numberOfTry < maxTotalIterations); if (numberOfTry >= maxTotalIterations) { throw new CannotCreatePopulationWithConstraintsException(_reportGenerator.StringReportFor(populationSettings)); } addUserDefinedVariabilityAndOntogenyForMolecules(randomPopulation); randomPopulation.IsLoaded = true; return(randomPopulation); } }, cancellationToken); return(task); }
private void initializeProgress(SimulationRunOptions options) { _populationRunner.Terminated += terminated; _populationRunner.SimulationProgress += simulationProgress; _progressUpdater = options.ShowProgress ? _progressManager.Create() : new NoneProgressUpdater(); }
public Task <RandomPopulation> CreateFor(RandomPopulationSettings populationSettings, CancellationToken cancellationToken, int?seed = null, bool addMoleculeParametersVariability = true) { return(Task.Run(() => { using (var progressUpdater = _progressManager.Create()) { var randomPopulation = createPopulationFor(populationSettings, seed); fllUpGenderQueueBasedOn(populationSettings); progressUpdater.Initialize(populationSettings.NumberOfIndividuals, PKSimConstants.UI.CreatingPopulation); var diseaseStateImplementation = _diseaseStateImplementationFactory.CreateFor(populationSettings.BaseIndividual); //the base individual is used to retrieve the default values. var baseIndividual = diseaseStateImplementation.CreateBaseIndividualForPopulation(populationSettings.BaseIndividual); //current individual defined as a clone of the based individual. The current individual will be the one varying var currentIndividual = _cloner.Clone(baseIndividual); //cache containing all parameters changed by the create individual from the current individual. This will be used just as reference to the current parameters var allChangedByCreatedIndividualParameters = getAllCreateIndividualParametersFrom(currentIndividual); //all distributed parameters. This will be used to update the distribution for the current individual var allDistributedParameters = getAllDistributedParametersFrom(currentIndividual); var allBaseDistributedParameters = getAllDistributedParametersFrom(baseIndividual); //all individual parameters. Just an optimization to avoid call GetAllChildren for each individual var allCurrentIndividualParameters = currentIndividual.GetAllChildren <IParameter>(); int maxTotalIterations = populationSettings.NumberOfIndividuals * _maxIterations; uint numberOfTry = 0; var currentGender = _genderQueue.Dequeue(); do { cancellationToken.ThrowIfCancellationRequested(); numberOfTry++; //could not create one item in max Iteration try=>exit if (numberOfTry > _maxIterations && randomPopulation.NumberOfItems == 0) { throw new CannotCreatePopulationWithConstraintsException(_reportGenerator.StringReportFor(populationSettings)); } //create a new individual based on population settings defined by the user updateCurrentIndividualFromSettings(populationSettings, baseIndividual, currentIndividual, allDistributedParameters, allBaseDistributedParameters, currentGender, randomPopulation.RandomGenerator); var success = tryRandomize(currentIndividual, populationSettings, allCurrentIndividualParameters, randomPopulation.RandomGenerator); if (!success) { continue; } success = diseaseStateImplementation.ApplyForPopulationTo(currentIndividual); if (!success) { continue; } randomPopulation.AddIndividualValues(_individualValuesMapper.MapFrom(currentIndividual, allChangedByCreatedIndividualParameters)); diseaseStateImplementation.ResetParametersAfterPopulationIteration(currentIndividual); currentGender = _genderQueue.Dequeue(); progressUpdater.IncrementProgress(PKSimConstants.UI.CreatingIndividualInPopulation(randomPopulation.NumberOfItems, populationSettings.NumberOfIndividuals)); } while (randomPopulation.NumberOfItems < populationSettings.NumberOfIndividuals && numberOfTry < maxTotalIterations); if (numberOfTry >= maxTotalIterations) { throw new CannotCreatePopulationWithConstraintsException(_reportGenerator.StringReportFor(populationSettings)); } if (addMoleculeParametersVariability) { _moleculeParameterVariabilityCreator.AddVariabilityTo(randomPopulation); } _moleculeOntogenyVariabilityUpdater.UpdateAllOntogenies(randomPopulation); randomPopulation.IsLoaded = true; return randomPopulation; } }, cancellationToken)); }
private void initializeProgress(ISensitivityAnalysisEngine sensitivityAnalysisEngine, SensitivityAnalysisRunOptions options) { sensitivityAnalysisEngine.Terminated += terminated; sensitivityAnalysisEngine.SimulationProgress += simulationProgress; _progressUpdater = options.ShowProgress ? _progressManager.Create() : new NoneProgressUpdater(); }