diff --git a/src/PKSim.Assets.Images/PKSim.Assets.Images.csproj b/src/PKSim.Assets.Images/PKSim.Assets.Images.csproj index 5d6ea4ee3..d295772ae 100644 --- a/src/PKSim.Assets.Images/PKSim.Assets.Images.csproj +++ b/src/PKSim.Assets.Images/PKSim.Assets.Images.csproj @@ -23,8 +23,8 @@ - - + + diff --git a/src/PKSim.Assets/PKSim.Assets.csproj b/src/PKSim.Assets/PKSim.Assets.csproj index 5e8c41600..e24980991 100644 --- a/src/PKSim.Assets/PKSim.Assets.csproj +++ b/src/PKSim.Assets/PKSim.Assets.csproj @@ -22,9 +22,9 @@ - - - + + + diff --git a/src/PKSim.Assets/PKSimConstants.cs b/src/PKSim.Assets/PKSimConstants.cs index 29733e6ae..604c8f495 100644 --- a/src/PKSim.Assets/PKSimConstants.cs +++ b/src/PKSim.Assets/PKSimConstants.cs @@ -466,22 +466,16 @@ public static string SaturationEnabledCanOnlyBeUsedForOralApplicationUsingPartic public static string CouldNotFindOutputInSimulation(string outputFullPath, string simulationName) => $"Cannot find output '{outputFullPath}' in simulation '{simulationName}'"; - public static string CouldNotFind(string objectType, string objectName) => $"Cannot find {objectType.ToLower()} '{objectName}'"; - - public static string CouldNotFindParameterIdentification(string parameterIdentificationName) => CouldNotFind(OSPSuite.Assets.ObjectTypes.ParameterIdentification, parameterIdentificationName); - - public static string CouldNotFindQualificationStep(string qualificationStepType) => CouldNotFind(ObjectTypes.QualificationStep, qualificationStepType); - - public static string NotMappingDefinedForQualificationStep(string qualificationStepType) => $"No mapping defined for {ObjectTypes.QualificationStep.ToLower()} '{qualificationStepType}'"; + public static string CouldNotFindParameterIdentification(string parameterIdentificationName) => OSPSuite.Assets.Error.CouldNotFind(OSPSuite.Assets.ObjectTypes.ParameterIdentification, parameterIdentificationName); public static string TableFormulationRequiresAtLeastOnePoint(string formulation) => $"Table formulation '{formulation}' requires at least one point to be used in a simulation."; - public static string CouldNotFindSimulation(string simulationName) => CouldNotFind(OSPSuite.Assets.ObjectTypes.Simulation, simulationName); + public static string CouldNotFindSimulation(string simulationName) => OSPSuite.Assets.Error.CouldNotFind(OSPSuite.Assets.ObjectTypes.Simulation, simulationName); public static string CannotCreateIdentificationParameter(string parameterPath, string parameterIdentificationName) => $"Cannot create identification parameter '{parameterPath}' for parameter identification '{parameterIdentificationName}'."; - public static string ParameterIsRequired(string parameterName) => CouldNotFind(OSPSuite.Assets.ObjectTypes.Parameter, parameterName); + public static string ParameterIsRequired(string parameterName) => OSPSuite.Assets.Error.CouldNotFind(OSPSuite.Assets.ObjectTypes.Parameter, parameterName); public static string SimulationResultsFileDoesNotHaveTheExpectedFormat { @@ -833,13 +827,9 @@ public static string ComparisonBetweenBuildingBLocksNotSupportedForBuildingBlock public static string CannotExtractIndividualFrom(string objectType) => $"Individual extraction is not available for '{objectType}'."; - public static string SnapshotNotFoundFor(string modelTypeName) => $"Snapshot not found for '{modelTypeName}'."; - public static string SnapshotParameterNotFoundInContainer(string parameterName, string container) => $"Snapshot parameter '{parameterName}' was not found in '{container}'."; public static string SnapshotParameterNotFound(string parameterName) => $"Snapshot parameter '{parameterName}' was not found."; - - public const string SnapshotIsOutdated = "Snapshot is outdated and cannot be loaded for the following reason: "; public static string MoleculeTypeNotSupported(string moleculeType) => $"Molecule type '{moleculeType}' not supported."; @@ -853,16 +843,6 @@ public static string ComparisonBetweenBuildingBLocksNotSupportedForBuildingBlock public static string SnapshotProcessNameNotFound(string processName) => $"Snapshot process '{processName}' not found in the PK-Sim database."; - public static string MapToModelNotSupportedWithoutContext(string modelType, string contextType) - { - return $"{modelType} should not be created from snapshot directly. Instead use the overload with {contextType}."; - } - - public static string MapToSnapshotNotSupportedWithoutContext(string snapshotType, string contextType) - { - return $"{snapshotType} should not be created from model directly. Instead use the overload with {contextType}."; - } - public const string PopulationSnapshotOnlySupportedForRandomPopulation = "Population snapshot can only be created for randomized population."; public const string SimulationSubjectUndefinedInSnapshot = "Simulation subject (Individual or Population) is not defined in snapshot."; @@ -873,16 +853,12 @@ public static string MapToSnapshotNotSupportedWithoutContext(string snapshotType public static string OnlyPKSimSimulationCanBeExportedToSnapshot(string simulationName, string origin) => $"Snapshot export is not supported for {origin} simulation '{simulationName}'."; - public static string SnapshotFileMismatch(string desiredType) => $"Snapshot file cannot be used to load a {desiredType.ToLowerInvariant()}."; - public static string CannotLoadRelatedItemAsObjectAlreadyExistInProject(string objectType, string objectName) => $"Cannot load related item into project. A {objectType.ToLower()} named '{objectName}' already exists."; public static string CompoundGroupNotFoundFor(string compoundGroup, string compoundName) => $"Cannot find compound group '{compoundGroup}' for compound '{compoundName}'"; public static string CompoundAlternativeNotFoundFor(string alternativeName, string defaultAlternativeName, string compoundGroup, string compoundName) => $"Cannot find alternative '{alternativeName}' in compound group '{compoundGroup}' for compound '{compoundName}'. Default alternative '{defaultAlternativeName}' will be used instead"; - public static string UnableToFindAQualificationStepRunnerFor(string qualificationStep) => $"Cannot find {ObjectTypes.QualificationStep} runner for '{qualificationStep}'"; - public static string CannotLoadSimulation(string simulationName) => $"Cannot load {ObjectTypes.Simulation} '{simulationName}'"; public static string UnableToLoadQualificationConfigurationFromFile(string fileFullPath) => $"Unable to read configuration from file '{fileFullPath}'"; @@ -1063,19 +1039,7 @@ public static string ObservedDataYAsTooltip(string y, string lowerValue, string return $"{ObservedDataYAsTooltip(y)}\n{TimeProfileYAsTooltip(lowerValue, upperValue)}"; } - public static string Starting(string type, string name) => $"Starting {type.ToLower()} '{name}'..."; - public static string ObservedDataYAsTooltip(string y) => ScatterYAsTooltip(y); - - public static string LoadingSnapshot(string snapshotFile, string type) => $"Loading {type} from {ObjectTypes.Snapshot.ToLower()} file '{snapshotFile}'"; - - public static string SnapshotLoaded(string typeToLoad) => $"{typeToLoad} loaded from {ObjectTypes.Snapshot.ToLower()}"; - - public static string LoadingSimulation(string simulationName, int count, int total) => $"Loading simulation '{simulationName}' ({count}/{total})..."; - - public static string StartingQualificationPlan(string qualificationPlan) => Starting(ObjectTypes.QualificationPlan, qualificationPlan); - - public static string StartingQualificationStep(string qualificationStep) => Starting(ObjectTypes.QualificationStep, qualificationStep); } public static class MenuNames @@ -1110,10 +1074,7 @@ public static class MenuNames public static readonly string About = "&About..."; public static readonly string OpenProject = "&Open..."; public static readonly string ProjectDescription = "&Description..."; - public static readonly string ExportProjectToSnapshot = "Export to Snapshot"; - public static readonly string LoadProjectFromSnapshot = "Load from Snapshot"; - public static readonly string ExportProjectToSnapshotMenu = $"&{ExportProjectToSnapshot}..."; - public static readonly string LoadProjectFromSnapshotMenu = $"{LoadProjectFromSnapshot}..."; + public static readonly string Clone = "Clone..."; public static readonly string CloneMenu = "Clone"; public static readonly string ActivateSimulation = "Set as Active Simulation"; @@ -1272,9 +1233,6 @@ public static class ObjectTypes public static readonly string Species = "Species"; public static readonly string SimulationAnalysisWorkflow = "Analysis"; public static readonly string IndividualOrPopulation = $"{Individual} or {Population}"; - public static readonly string QualificationStep = "Qualification Step"; - public static readonly string QualificationPlan = "Qualification Plan"; - public static readonly string Snapshot = "Snapshot"; public static readonly string ObserverSet = "Observers"; public static readonly string ExpressionProfile = "Expression Profile"; public static readonly string DiseaseState = "Disease State"; @@ -1622,8 +1580,7 @@ public static class UI public static readonly string OpeningProjectDatabase = "Opening project database..."; public static readonly string CreatingProjectDatabase = "Creating project database..."; public static readonly string LoadingProject = "Loading project..."; - public static readonly string LoadingSnapshot = "Loading snapshot..."; - public static readonly string SnapshotFile = "Select snapshot file"; + public static readonly string SavingProject = "Saving project..."; public static readonly string LoadingHistory = "Loading history..."; public static readonly string LoadingLayout = "Loading layout..."; @@ -1858,8 +1815,6 @@ public static class UI public static readonly string NewProjectDescription = "Create a new project..."; public static readonly string OpenProjectDescription = "Open an existing project..."; public static readonly string ProjectDescriptionDescription = "Show or edit project description..."; - public static readonly string ExportProjectToSnapshotDescription = "Export project to snapshot..."; - public static readonly string LoadProjectFromSnapshotDescription = "Load project from snapshot..."; public static readonly string CloseProjectDescription = "Close the project"; public static readonly string NewSimulationDescription = "Create a new simulation..."; public static readonly string ImportIndividualSimulationDescription = "Import an individual simulation from file..."; @@ -2070,7 +2025,7 @@ public static class UI public static readonly string Range = "Range"; public static readonly string ImportFolder = "Import all files from a specific folder"; public static readonly string ImportFiles = "Import single files"; - public static readonly string StartImport = "Start Import"; + public static readonly string Browse = "Browse"; public static readonly string SelectFolderContainingSimulationResults = "Select folder containing the results to import"; public static readonly string FileSuccessfullyImported = "File successfully imported"; @@ -2215,16 +2170,10 @@ public static class UI public static readonly string GlobalPKAnalysisDescription = "The median value calculated from all individual values"; public static readonly string[] DefaultExpressionProfileCategories = { Healthy }; - - public static string DoYouWantToProceed(params string[] messages) => $"WARNING:\n{messages.ToString("\n")}\n\nDo you wish to continue?"; - - private static readonly string _snapshotOfProjectWithChangedSimulationText = "Some simulations are in a changed state (red icon) and may not be re-imported correctly."; + public static readonly string SnapshotOfProjectCreatedWithEarlierVersion = OSPSuite.Assets.Captions.DoYouWantToProceed(_snapshotOfProjectCreatedWithEarlierVersionText); + public static readonly string SnapshotOfProjectCreatedWithEarlierVersionAndWithChangedSimulation = OSPSuite.Assets.Captions.DoYouWantToProceed(_snapshotOfProjectCreatedWithEarlierVersionText, OSPSuite.Assets.Captions.SnapshotOfProjectWithChangedSimulationText); private static readonly string _snapshotOfProjectCreatedWithEarlierVersionText = "Project was created with an older version of PK-Sim (earlier than 7.3.0). The created snapshot file will likely be incomplete. Only use if you know what you are doing!"; - public static readonly string SnapshotOfProjectWithChangedSimulation = DoYouWantToProceed(_snapshotOfProjectWithChangedSimulationText); - public static readonly string SnapshotOfProjectCreatedWithEarlierVersion = DoYouWantToProceed(_snapshotOfProjectCreatedWithEarlierVersionText); - public static readonly string SnapshotOfProjectCreatedWithEarlierVersionAndWithChangedSimulation = DoYouWantToProceed(_snapshotOfProjectCreatedWithEarlierVersionText, _snapshotOfProjectWithChangedSimulationText); - public static string NumberOfIndividualsToExtract(int count, string populationName) => $"{count} {"individual".PluralizeIf(count)} will be extracted from population {populationName}."; public static string IndividualExtractionNamingPatternDescription(string populationNamePattern, string individualIdPattern) @@ -2555,14 +2504,9 @@ public static string DragFieldMessage(string fieldType) public static string FilterAreaDragFieldMessage() => "Drag a field here to remove grouping"; public static readonly string ChartYScale = "Chart Y Scale"; - - public static string SelectSnapshotExportFile(string objectName, string objectType) => $"Export snapshot for {objectType.ToLowerInvariant()} '{objectName}'"; - - public static string LoadObjectFromSnapshot(string objectType) => $"Load {objectType.ToLowerInvariant()} from snapshot"; - - public static string LoadFromSnapshot = "Load Snapshot"; + public static string SelectExpressionProfile = "Select an expression profile"; - public static string RunSimulations = "Run Simulations"; + public static string NumberOfTemplatesSelectedIs(int number, string templateType) => $"{number} {templateType.PluralizeIf(number).ToLowerInvariant()} selected"; @@ -2575,7 +2519,7 @@ public static string UserTemplateDatabaseDatabaseUsedOldFormatAndCannotBeLoaded( "If you don't make a backup, you will be the only one to blame!" }; - public static readonly string ReallyClearUnusedContent = DoYouWantToProceed(_reallyClearUnusedContent); + public static readonly string ReallyClearUnusedContent = OSPSuite.Assets.Captions.DoYouWantToProceed(_reallyClearUnusedContent); public static readonly string DidYouReallyBackupProject = "Did you really make a backup of your project?"; public static string LinkedExpressionProfileIs(string expressionProfileName) => $"Using expression profile {expressionProfileName}"; diff --git a/src/PKSim.BatchTool/PKSim.BatchTool.csproj b/src/PKSim.BatchTool/PKSim.BatchTool.csproj index 972d41d69..63b8ca8b2 100644 --- a/src/PKSim.BatchTool/PKSim.BatchTool.csproj +++ b/src/PKSim.BatchTool/PKSim.BatchTool.csproj @@ -60,8 +60,8 @@ - - + + diff --git a/src/PKSim.BatchTool/Presenters/FolderListSnapshotPresenter.cs b/src/PKSim.BatchTool/Presenters/FolderListSnapshotPresenter.cs index 92446e061..5c9fcd2a3 100644 --- a/src/PKSim.BatchTool/Presenters/FolderListSnapshotPresenter.cs +++ b/src/PKSim.BatchTool/Presenters/FolderListSnapshotPresenter.cs @@ -3,12 +3,12 @@ using System.Linq; using Newtonsoft.Json; using OSPSuite.Core.Services; +using OSPSuite.Infrastructure.Serialization.Json; using OSPSuite.Presentation.Presenters; using PKSim.BatchTool.DTO; using PKSim.BatchTool.Views; using PKSim.CLI.Core.RunOptions; using PKSim.Core; -using PKSim.Infrastructure.Serialization.Json; namespace PKSim.BatchTool.Presenters { @@ -58,15 +58,9 @@ public void AddFolder(string folder) _snapshotFolderListDTO.CurrentFolder = string.Empty; } - public void RemoveFolder(FolderDTO folderDTO) - { - _snapshotFolderListDTO.RemoveFolder(folderDTO); - } + public void RemoveFolder(FolderDTO folderDTO) => _snapshotFolderListDTO.RemoveFolder(folderDTO); - public void ClearFolderList() - { - _snapshotFolderListDTO.ClearList(); - } + public void ClearFolderList() => _snapshotFolderListDTO.ClearList(); public void ImportFolderList() { @@ -75,7 +69,7 @@ public void ImportFolderList() return; ClearFolderList(); - var settings = new PKSimJsonSerializerSettings(); + var settings = new OSPSuiteJsonSerializerSettings(); var folders = JsonConvert.DeserializeObject>(File.ReadAllText(file), settings); _snapshotFolderListDTO.AddFolders(folders); } @@ -86,7 +80,7 @@ public void ExportFolderList() if (string.IsNullOrEmpty(file)) return; - var settings = new PKSimJsonSerializerSettings(); + var settings = new OSPSuiteJsonSerializerSettings(); File.WriteAllText(file, JsonConvert.SerializeObject(_snapshotFolderListDTO.Folders.Select(x => x.Folder), Formatting.Indented, settings)); } diff --git a/src/PKSim.CLI.Core/PKSim.CLI.Core.csproj b/src/PKSim.CLI.Core/PKSim.CLI.Core.csproj index 7bef6823a..6e78a1400 100644 --- a/src/PKSim.CLI.Core/PKSim.CLI.Core.csproj +++ b/src/PKSim.CLI.Core/PKSim.CLI.Core.csproj @@ -23,9 +23,9 @@ - + - + diff --git a/src/PKSim.CLI/PKSim.CLI.csproj b/src/PKSim.CLI/PKSim.CLI.csproj index ece48a8b1..d4ceaf4e0 100644 --- a/src/PKSim.CLI/PKSim.CLI.csproj +++ b/src/PKSim.CLI/PKSim.CLI.csproj @@ -55,9 +55,9 @@ - - - + + + diff --git a/src/PKSim.Core/CoreRegister.cs b/src/PKSim.Core/CoreRegister.cs index c8d02be17..e5621677b 100644 --- a/src/PKSim.Core/CoreRegister.cs +++ b/src/PKSim.Core/CoreRegister.cs @@ -7,9 +7,9 @@ using OSPSuite.Core.Domain.Services.ParameterIdentifications; using OSPSuite.Core.Domain.UnitSystem; using OSPSuite.Core.Maths.Interpolations; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Container; using OSPSuite.Utility.Data; -using OSPSuite.Infrastructure.Import.Services; using PKSim.Core.Comparison; using PKSim.Core.Mappers; using PKSim.Core.Model; @@ -23,7 +23,7 @@ public class CoreRegister : Register { public override void RegisterInContainer(IContainer container) { - container.AddRegister(x => x.FromInstance(new OSPSuite.Core.CoreRegister {RegisterParameter = false})); + container.AddRegister(x => x.FromInstance(new OSPSuite.Core.CoreRegister { RegisterParameter = false })); //Register PKSim.Core container.AddScanner(scan => @@ -41,12 +41,12 @@ public override void RegisterInContainer(IContainer container) scan.ExcludeType(); scan.ExcludeType(); scan.ExcludeType(); - + //Do not register the InteractiveSimulationRunner as it should be registered only if needed scan.ExcludeType(); - scan.ExcludeType(); scan.ExcludeNamespaceContainingType(); + scan.ExcludeNamespaceContainingType(); scan.WithConvention(); }); @@ -58,15 +58,22 @@ public override void RegisterInContainer(IContainer container) scan.IncludeType(); scan.IncludeType(); scan.IncludeType(); - scan.IncludeType(); scan.IncludeType(); scan.RegisterAs(LifeStyle.Singleton); scan.WithConvention(); }); - + + // Registered to satisfy the repository of ISnapshotMapperSpecification + container.AddScanner(scan => + { + scan.AssemblyContainingType(); + scan.IncludeNamespaceContainingType(); + scan.WithConvention>(); + }); + container.Register(); - container.Register(LifeStyle.Transient); + container.Register(LifeStyle.Transient); container.Register>(); container.Register, IndividualSimulationEngine>(LifeStyle.Transient); container.Register, PopulationSimulationEngine>(LifeStyle.Transient); diff --git a/src/PKSim.Core/Model/IQualificationStep.cs b/src/PKSim.Core/Model/IQualificationStep.cs deleted file mode 100644 index f5f545d4a..000000000 --- a/src/PKSim.Core/Model/IQualificationStep.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace PKSim.Core.Model -{ - public interface IQualificationStep - { - string Display { get; } - } -} \ No newline at end of file diff --git a/src/PKSim.Core/Model/QualificationPlan.cs b/src/PKSim.Core/Model/QualificationPlan.cs deleted file mode 100644 index 3373783c0..000000000 --- a/src/PKSim.Core/Model/QualificationPlan.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using OSPSuite.Core.Domain; - -namespace PKSim.Core.Model -{ - public class QualificationPlan : ObjectBase, IEnumerable - { - private readonly List _allQualificationSteps = new List(); - - public void Add(IQualificationStep qualificationStep) - { - _allQualificationSteps.Add(qualificationStep); - } - - public IReadOnlyList Steps => _allQualificationSteps; - - public IEnumerator GetEnumerator() => _allQualificationSteps.GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} \ No newline at end of file diff --git a/src/PKSim.Core/Model/RunParameterIdentificationQualificationStep.cs b/src/PKSim.Core/Model/RunParameterIdentificationQualificationStep.cs index d474473ce..1221b312c 100644 --- a/src/PKSim.Core/Model/RunParameterIdentificationQualificationStep.cs +++ b/src/PKSim.Core/Model/RunParameterIdentificationQualificationStep.cs @@ -1,12 +1,12 @@ -using OSPSuite.Core.Domain.ParameterIdentifications; +using OSPSuite.Core.Domain; +using OSPSuite.Core.Domain.ParameterIdentifications; using PKSim.Assets; -namespace PKSim.Core.Model +namespace PKSim.Core.Model; + +public class RunParameterIdentificationQualificationStep : IQualificationStep { - public class RunParameterIdentificationQualificationStep : IQualificationStep - { - public ParameterIdentification ParameterIdentification { get; set; } + public ParameterIdentification ParameterIdentification { get; set; } - public string Display => PKSimConstants.QualificationSteps.RunParameterIdentification(ParameterIdentification.Name); - } + public string Display => PKSimConstants.QualificationSteps.RunParameterIdentification(ParameterIdentification.Name); } \ No newline at end of file diff --git a/src/PKSim.Core/Model/RunSimulationQualificationStep.cs b/src/PKSim.Core/Model/RunSimulationQualificationStep.cs index ee92ad574..a158094cc 100644 --- a/src/PKSim.Core/Model/RunSimulationQualificationStep.cs +++ b/src/PKSim.Core/Model/RunSimulationQualificationStep.cs @@ -1,12 +1,11 @@ -using PKSim.Assets; +using OSPSuite.Core.Domain; +using PKSim.Assets; -namespace PKSim.Core.Model -{ - public class RunSimulationQualificationStep : IQualificationStep - { - public Simulation Simulation { get; set; } +namespace PKSim.Core.Model; - public string Display => PKSimConstants.QualificationSteps.RunSimulation(Simulation.Name); +public class RunSimulationQualificationStep : IQualificationStep +{ + public Simulation Simulation { get; set; } - } + public string Display => PKSimConstants.QualificationSteps.RunSimulation(Simulation.Name); } \ No newline at end of file diff --git a/src/PKSim.Core/PKSim.Core.csproj b/src/PKSim.Core/PKSim.Core.csproj index 1a83d3da6..8849e0cdf 100644 --- a/src/PKSim.Core/PKSim.Core.csproj +++ b/src/PKSim.Core/PKSim.Core.csproj @@ -26,10 +26,10 @@ - - - - + + + + diff --git a/src/PKSim.Core/Services/IJsonSerializer.cs b/src/PKSim.Core/Services/IJsonSerializer.cs deleted file mode 100644 index 55ca17ae8..000000000 --- a/src/PKSim.Core/Services/IJsonSerializer.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace PKSim.Core.Services -{ - public interface IJsonSerializer - { - Task Serialize(object objectToSerialize, string fileName); - Task DeserializeAsArray(string fileName, Type objectType); - Task DeserializeAsArrayFromString(string jsonString, Type objectType); - Task DeserializeAsArrayFromString(string jsonString); - Task Deserialize(string fileName, Type objectType); - Task Deserialize(string fileName) where T : class; - Task DeserializeFromString(string jsonString, Type objectType); - Task DeserializeFromString(string jsonString) where T : class; - string Serialize(object objectToSerialize); - } -} \ No newline at end of file diff --git a/src/PKSim.Core/Services/IQualificationStepRunner.cs b/src/PKSim.Core/Services/IQualificationStepRunner.cs deleted file mode 100644 index 81860b73e..000000000 --- a/src/PKSim.Core/Services/IQualificationStepRunner.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading.Tasks; -using OSPSuite.Core.Services; -using OSPSuite.Utility.Extensions; -using PKSim.Assets; -using PKSim.Core.Model; - -namespace PKSim.Core.Services -{ - public interface IQualificationStepRunner : IDisposable - { - Task RunAsync(IQualificationStep qualificationStep); - } - - public abstract class QualificationStepRunner : IQualificationStepRunner where T : IQualificationStep - { - protected readonly IOSPSuiteLogger _logger; - - protected QualificationStepRunner(IOSPSuiteLogger logger) - { - _logger = logger; - } - - protected virtual void Cleanup() - { - } - - public async Task RunAsync(IQualificationStep qualificationStep) - { - _logger.AddDebug(PKSimConstants.Information.StartingQualificationStep(qualificationStep.Display)); - await RunAsync(qualificationStep.DowncastTo()); - } - - public abstract Task RunAsync(T qualificationStep); - - #region Disposable properties - - private bool _disposed; - - public void Dispose() - { - if (_disposed) return; - - Cleanup(); - GC.SuppressFinalize(this); - _disposed = true; - } - - ~QualificationStepRunner() - { - Cleanup(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/PKSim.Core/Services/ProjectSnapshotToSimulationMapper.cs b/src/PKSim.Core/Services/ProjectSnapshotToSimulationMapper.cs index 50f149974..72a976c46 100644 --- a/src/PKSim.Core/Services/ProjectSnapshotToSimulationMapper.cs +++ b/src/PKSim.Core/Services/ProjectSnapshotToSimulationMapper.cs @@ -3,6 +3,8 @@ using System.Text; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Mappers; +using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility; using OSPSuite.Utility.Exceptions; using PKSim.Assets; diff --git a/src/PKSim.Core/Services/QualificationStepRunnerFactory.cs b/src/PKSim.Core/Services/QualificationStepRunnerFactory.cs index b6f15c9fb..ceb1a93ad 100644 --- a/src/PKSim.Core/Services/QualificationStepRunnerFactory.cs +++ b/src/PKSim.Core/Services/QualificationStepRunnerFactory.cs @@ -1,35 +1,23 @@ using System; -using OSPSuite.Utility.Container; -using PKSim.Assets; +using OSPSuite.Core.Domain; +using OSPSuite.Core.Services; using PKSim.Core.Model; +using IContainer = OSPSuite.Utility.Container.IContainer; -namespace PKSim.Core.Services -{ - public interface IQualificationStepRunnerFactory - { - IQualificationStepRunner CreateFor(IQualificationStep qualificationStep); - } +namespace PKSim.Core.Services; - public class QualificationStepRunnerFactory: IQualificationStepRunnerFactory +public class QualificationStepRunnerFactory(IContainer container) : OSPSuite.Core.Services.QualificationStepRunnerFactory(container) +{ + public override IQualificationStepRunner CreateFor(IQualificationStep qualificationStep) { - private readonly IContainer _container; - - public QualificationStepRunnerFactory(IContainer container) + switch (qualificationStep) { - _container = container; + case RunParameterIdentificationQualificationStep _: + return _container.Resolve(); + case RunSimulationQualificationStep _: + return _container.Resolve(); } - public IQualificationStepRunner CreateFor(IQualificationStep qualificationStep) - { - switch (qualificationStep) - { - case RunParameterIdentificationQualificationStep _: - return _container.Resolve(); - case RunSimulationQualificationStep _: - return _container.Resolve(); - } - - throw new ArgumentException(PKSimConstants.Error.UnableToFindAQualificationStepRunnerFor(qualificationStep.GetType().Name)); - } + throw new ArgumentException(OSPSuite.Assets.Error.UnableToFindAQualificationStepRunnerFor(qualificationStep.GetType().Name)); } } \ No newline at end of file diff --git a/src/PKSim.Core/Services/QualiticationPlanRunner.cs b/src/PKSim.Core/Services/QualiticationPlanRunner.cs deleted file mode 100644 index 0973fa59a..000000000 --- a/src/PKSim.Core/Services/QualiticationPlanRunner.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Threading.Tasks; -using OSPSuite.Core.Services; -using PKSim.Assets; -using PKSim.Core.Model; - -namespace PKSim.Core.Services -{ - public interface IQualiticationPlanRunner - { - Task RunAsync(QualificationPlan qualificationPlan); - } - - public class QualiticationPlanRunner : IQualiticationPlanRunner - { - private readonly IQualificationStepRunnerFactory _qualificationStepRunnerFactory; - private readonly IOSPSuiteLogger _logger; - - public QualiticationPlanRunner(IQualificationStepRunnerFactory qualificationStepRunnerFactory, IOSPSuiteLogger logger) - { - _qualificationStepRunnerFactory = qualificationStepRunnerFactory; - _logger = logger; - } - - public async Task RunAsync(QualificationPlan qualificationPlan) - { - _logger.AddDebug(PKSimConstants.Information.StartingQualificationPlan(qualificationPlan.Name)); - - //this needs to be run in order. Await EACH run - foreach (var qualificationStep in qualificationPlan.Steps) - { - using (var runner = _qualificationStepRunnerFactory.CreateFor(qualificationStep)) - { - await runner.RunAsync(qualificationStep); - } - } - } - } -} \ No newline at end of file diff --git a/src/PKSim.Core/Services/SimulationToProjectSnapshotMapper.cs b/src/PKSim.Core/Services/SimulationToProjectSnapshotMapper.cs index a33d72bd4..38243e604 100644 --- a/src/PKSim.Core/Services/SimulationToProjectSnapshotMapper.cs +++ b/src/PKSim.Core/Services/SimulationToProjectSnapshotMapper.cs @@ -2,10 +2,11 @@ using System.Linq; using System.Text; using OSPSuite.Core.Domain; +using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility; using OSPSuite.Utility.Extensions; using PKSim.Core.Model; -using PKSim.Core.Snapshots.Mappers; using ModelSimulation = PKSim.Core.Model.Simulation; namespace PKSim.Core.Services; @@ -31,7 +32,7 @@ private PKSimProject createProjectFrom(ModelSimulation simulation) simulation.UsedBuildingBlocks.Select(x => pkSimProjectRetriever.Current.BuildingBlockById(x.TemplateId)).Each(x => addBuildingBlockAndDependents(x, project)); simulation.UsedObservedData.Select(pkSimProjectRetriever.Current.ObservedDataBy).Each(project.AddObservedData); - + project.AddBuildingBlock(simulation); return project; diff --git a/src/PKSim.Core/Snapshots/Mappers/AlternativeMapper.cs b/src/PKSim.Core/Snapshots/Mappers/AlternativeMapper.cs index bbc2f3c2d..b3b80e91b 100644 --- a/src/PKSim.Core/Snapshots/Mappers/AlternativeMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/AlternativeMapper.cs @@ -1,6 +1,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Formulas; +using OSPSuite.Core.Snapshots; using PKSim.Assets; using PKSim.Core.Model; using PKSim.Core.Repositories; diff --git a/src/PKSim.Core/Snapshots/Mappers/AxisMapper.cs b/src/PKSim.Core/Snapshots/Mappers/AxisMapper.cs index ff97d77fe..36ed51036 100644 --- a/src/PKSim.Core/Snapshots/Mappers/AxisMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/AxisMapper.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Repositories; using ModelAxis = OSPSuite.Core.Chart.Axis; using SnapshotAxis = PKSim.Core.Snapshots.Axis; diff --git a/src/PKSim.Core/Snapshots/Mappers/CalculationMethodCacheMapper.cs b/src/PKSim.Core/Snapshots/Mappers/CalculationMethodCacheMapper.cs index 527ed1239..90fc7fbc3 100644 --- a/src/PKSim.Core/Snapshots/Mappers/CalculationMethodCacheMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/CalculationMethodCacheMapper.cs @@ -2,6 +2,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Assets; using PKSim.Core.Model; @@ -9,109 +10,94 @@ using SnapshotCalculationMethodCache = PKSim.Core.Snapshots.CalculationMethodCache; using ModelCalculationMethodCache = OSPSuite.Core.Domain.CalculationMethodCache; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class CalculationMethodCacheSnapshotContext : SnapshotContext { - public class CalculationMethodCacheSnapshotContext : SnapshotContext - { - public ModelCalculationMethodCache CalculationMethodCache { get; } + public ModelCalculationMethodCache CalculationMethodCache { get; } - public CalculationMethodCacheSnapshotContext(ModelCalculationMethodCache calculationMethodCache, SnapshotContext baseContext) : base(baseContext) - { - CalculationMethodCache = calculationMethodCache; - } + public CalculationMethodCacheSnapshotContext(ModelCalculationMethodCache calculationMethodCache, SnapshotContext baseContext) : base(baseContext) + { + CalculationMethodCache = calculationMethodCache; } +} - public class CalculationMethodCacheMapper : SnapshotMapperBase +public class CalculationMethodCacheMapper : SnapshotMapperBase +{ + private readonly ICalculationMethodRepository _calculationMethodRepository; + private readonly ICalculationMethodCategoryRepository _calculationMethodCategoryRepository; + private readonly IOSPSuiteLogger _logger; + + public CalculationMethodCacheMapper( + ICalculationMethodRepository calculationMethodRepository, + ICalculationMethodCategoryRepository calculationMethodCategoryRepository, + IOSPSuiteLogger logger) { - private readonly ICalculationMethodRepository _calculationMethodRepository; - private readonly ICalculationMethodCategoryRepository _calculationMethodCategoryRepository; - private readonly IOSPSuiteLogger _logger; - - public CalculationMethodCacheMapper( - ICalculationMethodRepository calculationMethodRepository, - ICalculationMethodCategoryRepository calculationMethodCategoryRepository, - IOSPSuiteLogger logger) - { - _calculationMethodRepository = calculationMethodRepository; - _calculationMethodCategoryRepository = calculationMethodCategoryRepository; - _logger = logger; - } + _calculationMethodRepository = calculationMethodRepository; + _calculationMethodCategoryRepository = calculationMethodCategoryRepository; + _logger = logger; + } - public override Task MapToSnapshot(ModelCalculationMethodCache model) - { - return mapCalculationMethodsToSnapshot(model); - } + public override Task MapToSnapshot(ModelCalculationMethodCache model) => mapCalculationMethodsToSnapshot(model); - public virtual Task MapToSnapshot(ModelCalculationMethodCache model, string species) - { - return mapCalculationMethodsToSnapshot(model, species); - } + public virtual Task MapToSnapshot(ModelCalculationMethodCache model, string species) => mapCalculationMethodsToSnapshot(model, species); - private Task mapCalculationMethodsToSnapshot(ModelCalculationMethodCache model, string species = null) - { - return SnapshotFrom(model, snapshot => { addCalculationMethodsToSnapshot(snapshot, model, species); }); - } + private Task mapCalculationMethodsToSnapshot(ModelCalculationMethodCache model, string species = null) => + SnapshotFrom(model, snapshot => { addCalculationMethodsToSnapshot(snapshot, model, species); }); - private void addCalculationMethodsToSnapshot(SnapshotCalculationMethodCache snapshot, ModelCalculationMethodCache calculationMethodCache, string species) - { - calculationMethodCache.All().Each(cm => addCalculationMethodToSnapshot(snapshot, cm, species)); - } + private void addCalculationMethodsToSnapshot(SnapshotCalculationMethodCache snapshot, ModelCalculationMethodCache calculationMethodCache, string species) => + calculationMethodCache.All().Each(cm => addCalculationMethodToSnapshot(snapshot, cm, species)); - private void addCalculationMethodToSnapshot(SnapshotCalculationMethodCache snapshot, CalculationMethod calculationMethod, string species) - { - var category = _calculationMethodCategoryRepository.FindBy(calculationMethod.Category); + private void addCalculationMethodToSnapshot(SnapshotCalculationMethodCache snapshot, CalculationMethod calculationMethod, string species) + { + var category = _calculationMethodCategoryRepository.FindBy(calculationMethod.Category); - var allPossibleCalculationMethods = category.AllItems().ToList(); + var allPossibleCalculationMethods = category.AllItems().ToList(); - //only one CM in this category. Nothing to do - if (allPossibleCalculationMethods.Count <= 1) - return; + //only one CM in this category. Nothing to do + if (allPossibleCalculationMethods.Count <= 1) + return; - //all CM have the same name? they will never be displayed together - if (allPossibleCalculationMethods.Select(x => x.DisplayName).Distinct().Count() == 1) - return; + //all CM have the same name? they will never be displayed together + if (allPossibleCalculationMethods.Select(x => x.DisplayName).Distinct().Count() == 1) + return; - //only one calculation method exists for the given species. Nothing to do - if (!string.IsNullOrEmpty(species) && allPossibleCalculationMethods.Count(x => x.AllSpecies.Contains(species)) == 1) - return; + //only one calculation method exists for the given species. Nothing to do + if (!string.IsNullOrEmpty(species) && allPossibleCalculationMethods.Count(x => x.AllSpecies.Contains(species)) == 1) + return; - //at least one CM that can be used in two models or different names. We may have a choice here. save it - snapshot.Add(calculationMethod.Name); - } + //at least one CM that can be used in two models or different names. We may have a choice here. save it + snapshot.Add(calculationMethod.Name); + } - public override Task MapToModel(SnapshotCalculationMethodCache snapshot, CalculationMethodCacheSnapshotContext snapshotContext) - { - UpdateCalculationMethodCache(snapshotContext.CalculationMethodCache, snapshot); - return Task.FromResult(snapshotContext.CalculationMethodCache); - } + public override Task MapToModel(SnapshotCalculationMethodCache snapshot, CalculationMethodCacheSnapshotContext snapshotContext) + { + UpdateCalculationMethodCache(snapshotContext.CalculationMethodCache, snapshot); + return Task.FromResult(snapshotContext.CalculationMethodCache); + } - public virtual void UpdateCalculationMethodCache(IWithCalculationMethods withCalculationMethods, SnapshotCalculationMethodCache snapshot) - { - UpdateCalculationMethodCache(withCalculationMethods.CalculationMethodCache, snapshot); - } - - public virtual void UpdateCalculationMethodCache(ModelCalculationMethodCache calculationMethodCache, SnapshotCalculationMethodCache snapshot, bool oneCalculationMethodPerCategory = true) + public virtual void UpdateCalculationMethodCache(IWithCalculationMethods withCalculationMethods, SnapshotCalculationMethodCache snapshot) => + UpdateCalculationMethodCache(withCalculationMethods.CalculationMethodCache, snapshot); + + public virtual void UpdateCalculationMethodCache(ModelCalculationMethodCache calculationMethodCache, SnapshotCalculationMethodCache snapshot, bool oneCalculationMethodPerCategory = true) => + snapshot?.Each(cm => useCalculationMethodIn(calculationMethodCache, cm, oneCalculationMethodPerCategory)); + + private void useCalculationMethodIn(ModelCalculationMethodCache calculationMethodCache, string calculationMethodName, bool oneCalculationMethodPerCategory) + { + var calculationMethod = _calculationMethodRepository.FindByName(calculationMethodName); + if (calculationMethod == null) { - snapshot?.Each(cm => useCalculationMethodIn(calculationMethodCache, cm, oneCalculationMethodPerCategory)); + _logger.AddWarning(PKSimConstants.Error.CalculationMethodNotFound(calculationMethodName)); + return; } - private void useCalculationMethodIn(ModelCalculationMethodCache calculationMethodCache, string calculationMethodName, bool oneCalculationMethodPerCategory) + if (oneCalculationMethodPerCategory) { - var calculationMethod = _calculationMethodRepository.FindByName(calculationMethodName); - if (calculationMethod == null) - { - _logger.AddWarning(PKSimConstants.Error.CalculationMethodNotFound(calculationMethodName)); - return; - } - - if(oneCalculationMethodPerCategory) - { - var existingCalculationMethod = calculationMethodCache.CalculationMethodFor(calculationMethod.Category); - if (existingCalculationMethod != null) - calculationMethodCache.RemoveCalculationMethod(existingCalculationMethod); - } - - calculationMethodCache.AddCalculationMethod(calculationMethod); + var existingCalculationMethod = calculationMethodCache.CalculationMethodFor(calculationMethod.Category); + if (existingCalculationMethod != null) + calculationMethodCache.RemoveCalculationMethod(existingCalculationMethod); } + + calculationMethodCache.AddCalculationMethod(calculationMethod); } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/ChartMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ChartMapper.cs index 58233367e..4fabb3e37 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ChartMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ChartMapper.cs @@ -1,43 +1,43 @@ using System.Threading.Tasks; using OSPSuite.Core.Chart; +using OSPSuite.Core.Snapshots.Mappers; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class ChartSnapshotContext : SnapshotContext { - public class ChartSnapshotContext : SnapshotContext - { - public IChart Chart { get; } + public IChart Chart { get; } - public ChartSnapshotContext(IChart chart, SnapshotContext baseContext) : base(baseContext) - { - Chart = chart; - } + public ChartSnapshotContext(IChart chart, SnapshotContext baseContext) : base(baseContext) + { + Chart = chart; } +} - public class ChartMapper : ObjectBaseSnapshotMapperBase +public class ChartMapper : ObjectBaseSnapshotMapperBase +{ + public override Task MapToSnapshot(IChart chart, Chart snapshot) { - public override Task MapToSnapshot(IChart chart, Chart snapshot) - { - MapModelPropertiesToSnapshot(chart, snapshot); - snapshot.Settings = chart.ChartSettings; - snapshot.FontAndSize = chart.FontAndSize; - snapshot.IncludeOriginData = SnapshotValueFor(chart.IncludeOriginData); - snapshot.OriginText = SnapshotValueFor(chart.OriginText); - snapshot.PreviewSettings = SnapshotValueFor(chart.PreviewSettings); - snapshot.Title = SnapshotValueFor(chart.Title); - return Task.FromResult(snapshot); - } + MapModelPropertiesToSnapshot(chart, snapshot); + snapshot.Settings = chart.ChartSettings; + snapshot.FontAndSize = chart.FontAndSize; + snapshot.IncludeOriginData = SnapshotValueFor(chart.IncludeOriginData); + snapshot.OriginText = SnapshotValueFor(chart.OriginText); + snapshot.PreviewSettings = SnapshotValueFor(chart.PreviewSettings); + snapshot.Title = SnapshotValueFor(chart.Title); + return Task.FromResult(snapshot); + } - public override Task MapToModel(Chart snapshot, ChartSnapshotContext snapshotContext) - { - var chart = snapshotContext.Chart; - MapSnapshotPropertiesToModel(snapshot, chart); - chart.ChartSettings.UpdatePropertiesFrom(snapshot.Settings); - chart.FontAndSize.UpdatePropertiesFrom(snapshot.FontAndSize); - chart.IncludeOriginData = snapshot.IncludeOriginData.GetValueOrDefault(chart.IncludeOriginData); - chart.OriginText = snapshot.OriginText; - chart.PreviewSettings = snapshot.PreviewSettings.GetValueOrDefault(chart.PreviewSettings); - chart.Title = ModelValueFor(snapshot.Title); - return Task.FromResult(chart); - } + public override Task MapToModel(Chart snapshot, ChartSnapshotContext snapshotContext) + { + var chart = snapshotContext.Chart; + MapSnapshotPropertiesToModel(snapshot, chart); + chart.ChartSettings.UpdatePropertiesFrom(snapshot.Settings); + chart.FontAndSize.UpdatePropertiesFrom(snapshot.FontAndSize); + chart.IncludeOriginData = snapshot.IncludeOriginData.GetValueOrDefault(chart.IncludeOriginData); + chart.OriginText = snapshot.OriginText; + chart.PreviewSettings = snapshot.PreviewSettings.GetValueOrDefault(chart.PreviewSettings); + chart.Title = ModelValueFor(snapshot.Title); + return Task.FromResult(chart); } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/ClassificationMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ClassificationMapper.cs index b80495255..e9d3c5370 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ClassificationMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ClassificationMapper.cs @@ -2,68 +2,57 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Snapshots.Mappers; using ModelClassification = OSPSuite.Core.Domain.Classification; using SnapshotClassification = PKSim.Core.Snapshots.Classification; -namespace PKSim.Core.Snapshots.Mappers -{ - public class ClassificationSnapshotContext : SnapshotContext - { - public ClassificationType ClassificationType { get; } +namespace PKSim.Core.Snapshots.Mappers; - public ClassificationSnapshotContext(ClassificationType classificationType, SnapshotContext baseContext) : base(baseContext) - { - ClassificationType = classificationType; - } - } +public class ClassificationSnapshotContext(ClassificationType classificationType, SnapshotContext baseContext) : SnapshotContext(baseContext) +{ + public ClassificationType ClassificationType { get; } = classificationType; +} - public class ClassificationMapper : SnapshotMapperBase +public class ClassificationMapper : SnapshotMapperBase +{ + public override Task MapToModel(SnapshotClassification snapshot, ClassificationSnapshotContext snapshotContext) { - public override Task MapToModel(SnapshotClassification snapshot, ClassificationSnapshotContext snapshotContext) + var classification = new ModelClassification { - var classification = new ModelClassification - { - ClassificationType = snapshotContext.ClassificationType, - Name = snapshot.Name - }; + ClassificationType = snapshotContext.ClassificationType, + Name = snapshot.Name + }; - return Task.FromResult(classification); - } + return Task.FromResult(classification); + } - public override Task MapToSnapshot(ModelClassification model, ClassificationContext context) - { - return mapTreeFrom(model, context); - } + public override Task MapToSnapshot(ModelClassification model, ClassificationContext context) + { + return mapTreeFrom(model, context); + } - private async Task mapTreeFrom(ModelClassification classification, ClassificationContext context) - { - var root = await SnapshotFrom(classification, x => { x.Name = classification.Name; }); + private async Task mapTreeFrom(ModelClassification classification, ClassificationContext context) + { + var root = await SnapshotFrom(classification, x => { x.Name = classification.Name; }); - var childClassifications = childClassificationsFrom(classification, context.Classifications); - var childClassifiables = childClassifiablesFrom(classification, context.Classifiables); + var childClassifications = childClassificationsFrom(classification, context.Classifications); + var childClassifiables = childClassifiablesFrom(classification, context.Classifiables); - if (childClassifications.Any()) - root.Classifications = await Task.WhenAll(childClassifications.Select(x => mapTreeFrom(x, context))); + if (childClassifications.Any()) + root.Classifications = await Task.WhenAll(childClassifications.Select(x => mapTreeFrom(x, context))); - if (childClassifiables.Any()) - root.Classifiables = childClassifiables.ToArray(); + if (childClassifiables.Any()) + root.Classifiables = childClassifiables.ToArray(); - return root; - } + return root; + } - private string[] childClassifiablesFrom(ModelClassification classification, IReadOnlyCollection classifiables) - { - return childrenFrom(classification, classifiables).AllNames().ToArray(); - } + private string[] childClassifiablesFrom(ModelClassification classification, IReadOnlyCollection classifiables) => + childrenFrom(classification, classifiables).AllNames().ToArray(); - private static IReadOnlyList childClassificationsFrom(ModelClassification classification, IReadOnlyCollection classifications) - { - return childrenFrom(classification, classifications).ToList(); - } + private static IReadOnlyList childClassificationsFrom(ModelClassification classification, IReadOnlyCollection classifications) => + childrenFrom(classification, classifications).ToList(); - private static IEnumerable childrenFrom(ModelClassification classification, IReadOnlyCollection classifications) where T : IClassifiable - { - return classifications.Where(x => Equals(x.Parent, classification)); - } - } + private static IEnumerable childrenFrom(ModelClassification classification, IReadOnlyCollection classifications) where T : IClassifiable => + classifications.Where(x => Equals(x.Parent, classification)); } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/ClassificationSnapshotTask.cs b/src/PKSim.Core/Snapshots/Mappers/ClassificationSnapshotTask.cs index ed8453c94..ff22501b6 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ClassificationSnapshotTask.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ClassificationSnapshotTask.cs @@ -2,97 +2,90 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; using OSPSuite.Utility.Extensions; using PKSim.Core.Model; using ModelClassification = OSPSuite.Core.Domain.Classification; using SnapshotClassification = PKSim.Core.Snapshots.Classification; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public interface IClassificationSnapshotTask +{ + /// + /// Maps the into classifications and adds them to the project defined in . + /// Also added to the project will be classifiables contained in the classifications and those will have the subjects + /// configured correctly from the list of . + /// + /// + /// This is the type of classifiable that is created for each classifiable in each newly + /// created classification /> + /// + /// This is the type of the subject for the classifiable + Task UpdateProjectClassifications(SnapshotClassification[] snapshots, SnapshotContext snapshotContext, IReadOnlyCollection subjects) + where TClassifiable : Classifiable, new() where TSubject : IObjectBase; + + Task MapClassificationsToSnapshots(PKSimProject project) where TClassifiable : class, IClassifiableWrapper, new(); +} + +public class ClassificationSnapshotTask(ClassificationMapper classificationMapper) : IClassificationSnapshotTask { - public interface IClassificationSnapshotTask + public Task UpdateProjectClassifications(SnapshotClassification[] snapshots, SnapshotContext snapshotContext, IReadOnlyCollection subjects) + where TClassifiable : Classifiable, new() where TSubject : IObjectBase { - /// - /// Maps the into classifications and adds them to the project defined in . - /// Also added to the project will be classifiables contained in the classifications and those will have the subjects - /// configured correctly from the list of . - /// - /// - /// This is the type of classifiable that is created for each classifiable in each newly - /// created classification /> - /// - /// This is the type of the subject for the classifiable - Task UpdateProjectClassifications(SnapshotClassification[] snapshots, SnapshotContext snapshotContext, IReadOnlyCollection subjects) - where TClassifiable : Classifiable, new() where TSubject : IObjectBase; + if (snapshots == null) + return Task.FromResult(false); - Task MapClassificationsToSnapshots(PKSimProject project) where TClassifiable : class, IClassifiableWrapper, new(); + var tasks = snapshots.Select(snapshot => updateProjectFor(snapshot, subjects, snapshotContext)); + return Task.WhenAll(tasks); } - public class ClassificationSnapshotTask : IClassificationSnapshotTask + private async Task updateProjectFor(Classification snapshot, IReadOnlyCollection subjects, SnapshotContext snapshotContext, ModelClassification parent = null) + where TClassifiable : Classifiable, new() where TSubject : IObjectBase { - private readonly ClassificationMapper _classificationMapper; + var classification = await classificationMapper.MapToModel(snapshot, new ClassificationSnapshotContext(classificationTypeFor(), snapshotContext)); + classification.Parent = parent; + var project = snapshotContext.Project; + project.AddClassification(classification); - public ClassificationSnapshotTask(ClassificationMapper classificationMapper) + snapshot.Classifiables?.Each(snapshotClassifiable => { - _classificationMapper = classificationMapper; - } + var subject = subjects.FindByName(snapshotClassifiable); + if (subject != null) + { + var classifiable = project.GetOrCreateClassifiableFor(subject); + classifiable.Parent = classification; + } + }); - public Task UpdateProjectClassifications(SnapshotClassification[] snapshots, SnapshotContext snapshotContext, IReadOnlyCollection subjects) - where TClassifiable : Classifiable, new() where TSubject : IObjectBase + if (snapshot.Classifications != null) { - if (snapshots == null) - return Task.FromResult(false); - - var tasks = snapshots.Select(snapshot => updateProjectFor(snapshot, subjects, snapshotContext)); - return Task.WhenAll(tasks); + var tasks = snapshot.Classifications.Select(x => updateProjectFor(x, subjects, snapshotContext, classification)); + await Task.WhenAll(tasks); } + } - private async Task updateProjectFor(Classification snapshot, IReadOnlyCollection subjects, SnapshotContext snapshotContext, ModelClassification parent = null) - where TClassifiable : Classifiable, new() where TSubject : IObjectBase - { - var classification = await _classificationMapper.MapToModel(snapshot, new ClassificationSnapshotContext(classificationTypeFor(), snapshotContext)); - classification.Parent = parent; - var project = snapshotContext.Project; - project.AddClassification(classification); - - snapshot.Classifiables?.Each(snapshotClassifiable => - { - var subject = subjects.FindByName(snapshotClassifiable); - if (subject != null) - { - var classifiable = project.GetOrCreateClassifiableFor(subject); - classifiable.Parent = classification; - } - }); - - if (snapshot.Classifications != null) - { - var tasks = snapshot.Classifications.Select(x => updateProjectFor(x, subjects, snapshotContext, classification)); - await Task.WhenAll(tasks); - } - } + public Task MapClassificationsToSnapshots(PKSimProject project) where TClassifiable : class, IClassifiableWrapper, new() + { + var classifications = project.AllClassificationsByType(classificationTypeFor()).OfType().ToList(); + var classifiables = project.AllClassifiablesByType(); - public Task MapClassificationsToSnapshots(PKSimProject project) where TClassifiable : class, IClassifiableWrapper, new() + var context = new ClassificationContext { - var classifications = project.AllClassificationsByType(classificationTypeFor()).OfType().ToList(); - var classifiables = project.AllClassifiablesByType(); - - var context = new ClassificationContext - { - Classifications = classifications, - Classifiables = classifiables - }; + Classifications = classifications, + Classifiables = classifiables + }; - var rootClassifications = findRoots(classifications); + var rootClassifications = findRoots(classifications); - return _classificationMapper.MapToSnapshots(rootClassifications, context); - } + return classificationMapper.MapToSnapshots(rootClassifications, context); + } - private IEnumerable findRoots(IEnumerable classifications) where T : IClassifiable => classifications.Where(x => x.Parent == null); + private IEnumerable findRoots(IEnumerable classifications) where T : IClassifiable => classifications.Where(x => x.Parent == null); - private ClassificationType classificationTypeFor() where T : IClassifiable, new() - { - var classifiable = new T(); - return classifiable.ClassificationType; - } + private ClassificationType classificationTypeFor() where T : IClassifiable, new() + { + var classifiable = new T(); + return classifiable.ClassificationType; } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/CompoundMapper.cs b/src/PKSim.Core/Snapshots/Mappers/CompoundMapper.cs index ae0f646ff..79322c85e 100644 --- a/src/PKSim.Core/Snapshots/Mappers/CompoundMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/CompoundMapper.cs @@ -8,204 +8,204 @@ using static PKSim.Core.CoreConstants.Parameters; using SnapshotCompound = PKSim.Core.Snapshots.Compound; using ModelCompound = PKSim.Core.Model.Compound; +using static OSPSuite.Core.Extensions.SnapshotMapperBaseExtensions; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class CompoundMapper : ParameterContainerSnapshotMapperBase { - public class CompoundMapper : ParameterContainerSnapshotMapperBase - { - private readonly AlternativeMapper _alternativeMapper; - private readonly CalculationMethodCacheMapper _calculationMethodCacheMapper; - private readonly CompoundProcessMapper _processMapper; - private readonly ValueOriginMapper _valueOriginMapper; - private readonly ICompoundFactory _compoundFactory; - - public CompoundMapper( - ParameterMapper parameterMapper, - AlternativeMapper alternativeMapper, - CalculationMethodCacheMapper calculationMethodCacheMapper, - CompoundProcessMapper processMapper, - ValueOriginMapper valueOriginMapper, - ICompoundFactory compoundFactory) : base(parameterMapper) - { - _alternativeMapper = alternativeMapper; - _calculationMethodCacheMapper = calculationMethodCacheMapper; - _processMapper = processMapper; - _valueOriginMapper = valueOriginMapper; - _compoundFactory = compoundFactory; - } - - public override async Task MapToSnapshot(ModelCompound compound) - { - var snapshot = await SnapshotFrom(compound); - snapshot.CalculationMethods = await _calculationMethodCacheMapper.MapToSnapshot(compound.CalculationMethodCache); - snapshot.Lipophilicity = await mapAlternatives(compound, COMPOUND_LIPOPHILICITY); - snapshot.FractionUnbound = await mapAlternatives(compound, COMPOUND_FRACTION_UNBOUND); - snapshot.Solubility = await mapAlternatives(compound, COMPOUND_SOLUBILITY); - snapshot.IntestinalPermeability = await mapAlternatives(compound, COMPOUND_INTESTINAL_PERMEABILITY); - snapshot.Permeability = await mapAlternatives(compound, COMPOUND_PERMEABILITY); - snapshot.PkaTypes = await mapPkaTypes(compound); - snapshot.Processes = await mapProcesses(compound); - snapshot.IsSmallMolecule = compound.IsSmallMolecule; - snapshot.PlasmaProteinBindingPartner = SnapshotValueFor(compound.PlasmaProteinBindingPartner, PlasmaProteinBindingPartner.Unknown); - return snapshot; - } - - public override async Task MapToModel(SnapshotCompound snapshot, SnapshotContext snapshotContext) - { - var compound = _compoundFactory.Create(); - MapSnapshotPropertiesToModel(snapshot, compound); - _calculationMethodCacheMapper.UpdateCalculationMethodCache(compound, snapshot.CalculationMethods); + private readonly AlternativeMapper _alternativeMapper; + private readonly CalculationMethodCacheMapper _calculationMethodCacheMapper; + private readonly CompoundProcessMapper _processMapper; + private readonly ValueOriginMapper _valueOriginMapper; + private readonly ICompoundFactory _compoundFactory; + + public CompoundMapper( + ParameterMapper parameterMapper, + AlternativeMapper alternativeMapper, + CalculationMethodCacheMapper calculationMethodCacheMapper, + CompoundProcessMapper processMapper, + ValueOriginMapper valueOriginMapper, + ICompoundFactory compoundFactory) : base(parameterMapper) + { + _alternativeMapper = alternativeMapper; + _calculationMethodCacheMapper = calculationMethodCacheMapper; + _processMapper = processMapper; + _valueOriginMapper = valueOriginMapper; + _compoundFactory = compoundFactory; + } - await updateAlternatives(compound, snapshot.Lipophilicity, COMPOUND_LIPOPHILICITY, snapshotContext); - await updateAlternatives(compound, snapshot.FractionUnbound, COMPOUND_FRACTION_UNBOUND, snapshotContext); - await updateAlternatives(compound, snapshot.Solubility, COMPOUND_SOLUBILITY, snapshotContext); - await updateAlternatives(compound, snapshot.IntestinalPermeability, COMPOUND_INTESTINAL_PERMEABILITY, snapshotContext); - await updateAlternatives(compound, snapshot.Permeability, COMPOUND_PERMEABILITY, snapshotContext); + public override async Task MapToSnapshot(ModelCompound compound) + { + var snapshot = await SnapshotFrom(compound); + snapshot.CalculationMethods = await _calculationMethodCacheMapper.MapToSnapshot(compound.CalculationMethodCache); + snapshot.Lipophilicity = await mapAlternatives(compound, COMPOUND_LIPOPHILICITY); + snapshot.FractionUnbound = await mapAlternatives(compound, COMPOUND_FRACTION_UNBOUND); + snapshot.Solubility = await mapAlternatives(compound, COMPOUND_SOLUBILITY); + snapshot.IntestinalPermeability = await mapAlternatives(compound, COMPOUND_INTESTINAL_PERMEABILITY); + snapshot.Permeability = await mapAlternatives(compound, COMPOUND_PERMEABILITY); + snapshot.PkaTypes = await mapPkaTypes(compound); + snapshot.Processes = await mapProcesses(compound); + snapshot.IsSmallMolecule = compound.IsSmallMolecule; + snapshot.PlasmaProteinBindingPartner = SnapshotValueFor(compound.PlasmaProteinBindingPartner, PlasmaProteinBindingPartner.Unknown); + return snapshot; + } - updatePkaTypes(compound, snapshot); + public override async Task MapToModel(SnapshotCompound snapshot, SnapshotContext snapshotContext) + { + var compound = _compoundFactory.Create(); + MapSnapshotPropertiesToModel(snapshot, compound); + _calculationMethodCacheMapper.UpdateCalculationMethodCache(compound, snapshot.CalculationMethods); - await updateProcesses(snapshot, compound, snapshotContext); - await UpdateParametersFromSnapshot(snapshot, compound, snapshotContext); + await updateAlternatives(compound, snapshot.Lipophilicity, COMPOUND_LIPOPHILICITY, snapshotContext); + await updateAlternatives(compound, snapshot.FractionUnbound, COMPOUND_FRACTION_UNBOUND, snapshotContext); + await updateAlternatives(compound, snapshot.Solubility, COMPOUND_SOLUBILITY, snapshotContext); + await updateAlternatives(compound, snapshot.IntestinalPermeability, COMPOUND_INTESTINAL_PERMEABILITY, snapshotContext); + await updateAlternatives(compound, snapshot.Permeability, COMPOUND_PERMEABILITY, snapshotContext); - synchronizeMolWeightValueOrigins(compound); - return compound; - } + updatePkaTypes(compound, snapshot); - protected override void MapSnapshotPropertiesToModel(SnapshotCompound snapshot, ModelCompound compound) - { - base.MapSnapshotPropertiesToModel(snapshot, compound); - compound.IsSmallMolecule = ModelValueFor(snapshot.IsSmallMolecule, true); - compound.PlasmaProteinBindingPartner = ModelValueFor(snapshot.PlasmaProteinBindingPartner, PlasmaProteinBindingPartner.Unknown); - } + await updateProcesses(snapshot, compound, snapshotContext); + await UpdateParametersFromSnapshot(snapshot, compound, snapshotContext); - private async Task updateProcesses(SnapshotCompound snapshot, ModelCompound compound, SnapshotContext snapshotContext) - { - var processes = await _processMapper.MapToModels(snapshot.Processes, snapshotContext); - processes?.Each(compound.AddProcess); - } + synchronizeMolWeightValueOrigins(compound); + return compound; + } - private async Task updateAlternatives(ModelCompound compound, Alternative[] snapshotAlternatives, string alternativeGroupName, SnapshotContext snapshotContext) - { - if (snapshotAlternatives == null) - return; + protected override void MapSnapshotPropertiesToModel(SnapshotCompound snapshot, ModelCompound compound) + { + base.MapSnapshotPropertiesToModel(snapshot, compound); + compound.IsSmallMolecule = ModelValueFor(snapshot.IsSmallMolecule, true); + compound.PlasmaProteinBindingPartner = ModelValueFor(snapshot.PlasmaProteinBindingPartner, PlasmaProteinBindingPartner.Unknown); + } - var alternativeGroup = compound.ParameterAlternativeGroup(alternativeGroupName); + private async Task updateProcesses(SnapshotCompound snapshot, ModelCompound compound, SnapshotContext snapshotContext) + { + var processes = await _processMapper.MapToModels(snapshot.Processes, snapshotContext); + processes?.Each(compound.AddProcess); + } - //Remove all alternatives except calculated ones - alternativeGroup.AllAlternatives.ToList().Where(x => !x.IsCalculated).Each(alternativeGroup.RemoveAlternative); + private async Task updateAlternatives(ModelCompound compound, Alternative[] snapshotAlternatives, string alternativeGroupName, SnapshotContext snapshotContext) + { + if (snapshotAlternatives == null) + return; - //Reset the default flag that will be read from snapshot - alternativeGroup.AllAlternatives.Each(x => x.IsDefault = false); + var alternativeGroup = compound.ParameterAlternativeGroup(alternativeGroupName); - var alternativeSnapshotContext = new AlternativeMapperSnapshotContext(alternativeGroup, snapshotContext); - var alternatives = await _alternativeMapper.MapToModels(snapshotAlternatives, alternativeSnapshotContext); + //Remove all alternatives except calculated ones + alternativeGroup.AllAlternatives.ToList().Where(x => !x.IsCalculated).Each(alternativeGroup.RemoveAlternative); - alternatives?.Each(alternativeGroup.AddAlternative); + //Reset the default flag that will be read from snapshot + alternativeGroup.AllAlternatives.Each(x => x.IsDefault = false); - //Ensure that we have at least one default alternative (might not be the case if only calculated alternatives were saved) - var defaultAlternative = alternativeGroup.DefaultAlternative; - if (defaultAlternative != null) - defaultAlternative.IsDefault = true; - } + var alternativeSnapshotContext = new AlternativeMapperSnapshotContext(alternativeGroup, snapshotContext); + var alternatives = await _alternativeMapper.MapToModels(snapshotAlternatives, alternativeSnapshotContext); - private void updatePkaTypes(ModelCompound compound, SnapshotCompound snapshot) - { - snapshot.PkaTypes?.Each((pkaType, i) => updatePkaType(compound, pkaType, i)); - synchronizePkaValueOrigins(snapshot.PkaTypes?.FirstOrDefault(), compound); - } + alternatives?.Each(alternativeGroup.AddAlternative); - private void synchronizeMolWeightValueOrigins(ModelCompound compound) - { - //Mol weight parameter and halogens value share the same value origin and should be updated as such - var molWeight = compound.Parameter(MOLECULAR_WEIGHT); - var halogens = compound.AllParameters(x => x.NameIsOneOf(Halogens)); - halogens.Each(x => x.ValueOrigin.UpdateAllFrom(molWeight.ValueOrigin)); - } + //Ensure that we have at least one default alternative (might not be the case if only calculated alternatives were saved) + var defaultAlternative = alternativeGroup.DefaultAlternative; + if (defaultAlternative != null) + defaultAlternative.IsDefault = true; + } - private void synchronizePkaValueOrigins(PkaType pkaType, ModelCompound compound) - { - var valueOrigin = pkaType?.ValueOrigin; - if (valueOrigin == null) - return; - - //Making sure that all pKa parameters have the same value origin, even neutral ones - Enumerable.Range(0, CoreConstants.NUMBER_OF_PKA_PARAMETERS).Each(index => - { - var (compoundTypeParameter, pKaParameter) = pkaParametersFor(compound, index); - _valueOriginMapper.UpdateValueOrigin(compoundTypeParameter.ValueOrigin, valueOrigin); - _valueOriginMapper.UpdateValueOrigin(pKaParameter.ValueOrigin, valueOrigin); - }); - } - - private void updatePkaType(ModelCompound compound, PkaType pkaType, int index) + private void updatePkaTypes(ModelCompound compound, SnapshotCompound snapshot) + { + snapshot.PkaTypes?.Each((pkaType, i) => updatePkaType(compound, pkaType, i)); + synchronizePkaValueOrigins(snapshot.PkaTypes?.FirstOrDefault(), compound); + } + + private void synchronizeMolWeightValueOrigins(ModelCompound compound) + { + //Mol weight parameter and halogens value share the same value origin and should be updated as such + var molWeight = compound.Parameter(MOLECULAR_WEIGHT); + var halogens = compound.AllParameters(x => x.NameIsOneOf(Halogens)); + halogens.Each(x => x.ValueOrigin.UpdateAllFrom(molWeight.ValueOrigin)); + } + + private void synchronizePkaValueOrigins(PkaType pkaType, ModelCompound compound) + { + var valueOrigin = pkaType?.ValueOrigin; + if (valueOrigin == null) + return; + + //Making sure that all pKa parameters have the same value origin, even neutral ones + Enumerable.Range(0, CoreConstants.NUMBER_OF_PKA_PARAMETERS).Each(index => { var (compoundTypeParameter, pKaParameter) = pkaParametersFor(compound, index); + _valueOriginMapper.UpdateValueOrigin(compoundTypeParameter.ValueOrigin, valueOrigin); + _valueOriginMapper.UpdateValueOrigin(pKaParameter.ValueOrigin, valueOrigin); + }); + } - compoundTypeParameter.Value = (int) pkaType.Type; - pKaParameter.Value = pkaType.Pka; - } + private void updatePkaType(ModelCompound compound, PkaType pkaType, int index) + { + var (compoundTypeParameter, pKaParameter) = pkaParametersFor(compound, index); - private (IParameter compoundTypeParameter, IParameter pkaParameter) pkaParametersFor(ModelCompound compound, int index) - { - var compoundTypeParameter = compound.Parameter(Constants.Parameters.ParameterCompoundType(index)); - var pkaParameter = compound.Parameter(ParameterPKa(index)); - return (compoundTypeParameter, pkaParameter); - } + compoundTypeParameter.Value = (int)pkaType.Type; + pKaParameter.Value = pkaType.Pka; + } + + private (IParameter compoundTypeParameter, IParameter pkaParameter) pkaParametersFor(ModelCompound compound, int index) + { + var compoundTypeParameter = compound.Parameter(Constants.Parameters.ParameterCompoundType(index)); + var pkaParameter = compound.Parameter(ParameterPKa(index)); + return (compoundTypeParameter, pkaParameter); + } - private Task mapProcesses(ModelCompound compound) => _processMapper.MapToSnapshots(compound.AllProcesses()); + private Task mapProcesses(ModelCompound compound) => _processMapper.MapToSnapshots(compound.AllProcesses()); - private Task mapPkaTypes(ModelCompound compound) - { - return SnapshotMapperBaseExtensions.MapTo(Enumerable.Range(0, CoreConstants.NUMBER_OF_PKA_PARAMETERS), i => mapPkaType(compound, i)); - } + private Task mapPkaTypes(ModelCompound compound) + { + return MapTo(Enumerable.Range(0, CoreConstants.NUMBER_OF_PKA_PARAMETERS), i => mapPkaType(compound, i)); + } - private async Task mapPkaType(ModelCompound compound, int index) - { - var (compoundTypeParameter, pKaParameter) = pkaParametersFor(compound, index); - var pKa = pKaParameter.Value; - var compoundType = (CompoundType) compoundTypeParameter.Value; - if (compoundType == CompoundType.Neutral) - return null; + private async Task mapPkaType(ModelCompound compound, int index) + { + var (compoundTypeParameter, pKaParameter) = pkaParametersFor(compound, index); + var pKa = pKaParameter.Value; + var compoundType = (CompoundType)compoundTypeParameter.Value; + if (compoundType == CompoundType.Neutral) + return null; - var valueOrigin = await _valueOriginMapper.MapToSnapshot(pKaParameter.ValueOrigin); + var valueOrigin = await _valueOriginMapper.MapToSnapshot(pKaParameter.ValueOrigin); - return new PkaType {Pka = pKa, Type = compoundType, ValueOrigin = valueOrigin}; - } + return new PkaType { Pka = pKa, Type = compoundType, ValueOrigin = valueOrigin }; + } - protected override Task AddModelParametersToSnapshot(ModelCompound compound, SnapshotCompound snapshot) - { - var parameters = parameterOverwrittenByUserIn(compound); - return AddParametersToSnapshot(parameters, snapshot); - } + protected override Task AddModelParametersToSnapshot(ModelCompound compound, SnapshotCompound snapshot) + { + var parameters = parameterOverwrittenByUserIn(compound); + return AddParametersToSnapshot(parameters, snapshot); + } - private IReadOnlyList parameterOverwrittenByUserIn(ModelCompound compound) - { - var parameters = new List(); - //Molecular Weight - parameters.AddRange(changedGroupParameters(compound, COMPOUND_MW)); + private IReadOnlyList parameterOverwrittenByUserIn(ModelCompound compound) + { + var parameters = new List(); + //Molecular Weight + parameters.AddRange(changedGroupParameters(compound, COMPOUND_MW)); - //advanced parameters - parameters.AddRange(changedGroupParameters(compound, COMPOUND_TWO_PORE)); - parameters.AddRange(changedGroupParameters(compound, COMPOUND_DISSOLUTION)); + //advanced parameters + parameters.AddRange(changedGroupParameters(compound, COMPOUND_TWO_PORE)); + parameters.AddRange(changedGroupParameters(compound, COMPOUND_DISSOLUTION)); - return parameters; - } + return parameters; + } - private IEnumerable changedGroupParameters(IContainer container, string groupName) - { - return container.AllParameters(x => string.Equals(x.GroupName, groupName)) - .Where(ShouldExportParameterToSnapshot); - } + private IEnumerable changedGroupParameters(IContainer container, string groupName) + { + return container.AllParameters(x => string.Equals(x.GroupName, groupName)) + .Where(ShouldExportParameterToSnapshot); + } - private async Task mapAlternatives(ModelCompound compound, string alternativeGroupName) - { - var alternativeGroup = compound.ParameterAlternativeGroup(alternativeGroupName); - var alternatives = await _alternativeMapper.MapToSnapshots(alternativeGroup.AllAlternatives); - var definedAlternatives = alternatives?.ToArray(); - if (definedAlternatives == null || !definedAlternatives.Any()) - return null; - - return definedAlternatives; - } + private async Task mapAlternatives(ModelCompound compound, string alternativeGroupName) + { + var alternativeGroup = compound.ParameterAlternativeGroup(alternativeGroupName); + var alternatives = await _alternativeMapper.MapToSnapshots(alternativeGroup.AllAlternatives); + var definedAlternatives = alternatives?.ToArray(); + if (definedAlternatives == null || !definedAlternatives.Any()) + return null; + + return definedAlternatives; } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/CompoundPropertiesMapper.cs b/src/PKSim.Core/Snapshots/Mappers/CompoundPropertiesMapper.cs index 6ebdd3e43..db268899b 100644 --- a/src/PKSim.Core/Snapshots/Mappers/CompoundPropertiesMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/CompoundPropertiesMapper.cs @@ -4,243 +4,242 @@ using OSPSuite.Core.Domain; using OSPSuite.Core.Extensions; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Assets; using PKSim.Core.Model; using SnapshotCompoundProperties = PKSim.Core.Snapshots.CompoundProperties; using ModelCompoundProperties = PKSim.Core.Model.CompoundProperties; -namespace PKSim.Core.Snapshots.Mappers -{ - public class CompoundPropertiesMapper : SnapshotMapperBase - { - private readonly CalculationMethodCacheMapper _calculationMethodCacheMapper; - private readonly ProcessMappingMapper _processMappingMapper; - private readonly IOSPSuiteLogger _logger; +namespace PKSim.Core.Snapshots.Mappers; - public CompoundPropertiesMapper(CalculationMethodCacheMapper calculationMethodCacheMapper, ProcessMappingMapper processMappingMapper, IOSPSuiteLogger logger) - { - _calculationMethodCacheMapper = calculationMethodCacheMapper; - _processMappingMapper = processMappingMapper; - _logger = logger; - } +public class CompoundPropertiesMapper : SnapshotMapperBase +{ + private readonly CalculationMethodCacheMapper _calculationMethodCacheMapper; + private readonly ProcessMappingMapper _processMappingMapper; + private readonly IOSPSuiteLogger _logger; - public override async Task MapToSnapshot(ModelCompoundProperties modelCompoundProperties, PKSimProject project) - { - var compound = modelCompoundProperties.Compound; - var snapshot = await SnapshotFrom(modelCompoundProperties, x => - { - x.Name = compound.Name; - x.Alternatives = alternativeSelectionsFrom(compound, modelCompoundProperties); - x.Protocol = protocolPropertiesFrom(modelCompoundProperties.ProtocolProperties, project); - }); - - snapshot.CalculationMethods = await _calculationMethodCacheMapper.MapToSnapshot(modelCompoundProperties.CalculationMethodCache); - snapshot.Processes = await snapshotProcessSelectionFrom(modelCompoundProperties.Processes); - return snapshot; - } + public CompoundPropertiesMapper(CalculationMethodCacheMapper calculationMethodCacheMapper, ProcessMappingMapper processMappingMapper, IOSPSuiteLogger logger) + { + _calculationMethodCacheMapper = calculationMethodCacheMapper; + _processMappingMapper = processMappingMapper; + _logger = logger; + } - private ProtocolSelection protocolPropertiesFrom(ProtocolProperties protocolProperties, PKSimProject project) + public override async Task MapToSnapshot(ModelCompoundProperties modelCompoundProperties, PKSimProject project) + { + var compound = modelCompoundProperties.Compound; + var snapshot = await SnapshotFrom(modelCompoundProperties, x => { - if (protocolProperties.Protocol == null) - return null; + x.Name = compound.Name; + x.Alternatives = alternativeSelectionsFrom(compound, modelCompoundProperties); + x.Protocol = protocolPropertiesFrom(modelCompoundProperties.ProtocolProperties, project); + }); - return new ProtocolSelection - { - Name = protocolProperties.Protocol.Name, - Formulations = formulationMappingFrom(protocolProperties.FormulationMappings, project) - }; - } + snapshot.CalculationMethods = await _calculationMethodCacheMapper.MapToSnapshot(modelCompoundProperties.CalculationMethodCache); + snapshot.Processes = await snapshotProcessSelectionFrom(modelCompoundProperties.Processes); + return snapshot; + } - private Task snapshotProcessSelectionFrom(CompoundProcessesSelection compoundProcessesSelection) - { - return _processMappingMapper.MapToSnapshots(compoundProcessesSelection.AllProcesses()); - } + private ProtocolSelection protocolPropertiesFrom(ProtocolProperties protocolProperties, PKSimProject project) + { + if (protocolProperties.Protocol == null) + return null; - private CompoundGroupSelection[] alternativeSelectionsFrom(Model.Compound compound, ModelCompoundProperties modelCompoundProperties) + return new ProtocolSelection { - var alternativesSelections = new List(); - modelCompoundProperties.CompoundGroupSelections.Each(x => - { - var compoundProperties = compound.ParameterAlternativeGroup(x.GroupName); - if (compoundProperties.AllAlternatives.Count() > 1) - alternativesSelections.Add(x); - }); + Name = protocolProperties.Protocol.Name, + Formulations = formulationMappingFrom(protocolProperties.FormulationMappings, project) + }; + } - return !alternativesSelections.Any() ? null : alternativesSelections.ToArray(); - } + private Task snapshotProcessSelectionFrom(CompoundProcessesSelection compoundProcessesSelection) + { + return _processMappingMapper.MapToSnapshots(compoundProcessesSelection.AllProcesses()); + } - private FormulationSelection[] formulationMappingFrom(IReadOnlyList formulationMappings, PKSimProject project) + private CompoundGroupSelection[] alternativeSelectionsFrom(Model.Compound compound, ModelCompoundProperties modelCompoundProperties) + { + var alternativesSelections = new List(); + modelCompoundProperties.CompoundGroupSelections.Each(x => { - if (!formulationMappings.Any()) - return null; + var compoundProperties = compound.ParameterAlternativeGroup(x.GroupName); + if (compoundProperties.AllAlternatives.Count() > 1) + alternativesSelections.Add(x); + }); - return formulationMappings - .Select(x => formulationSelectionFrom(x, project)) - .ToArray(); - } + return !alternativesSelections.Any() ? null : alternativesSelections.ToArray(); + } - private FormulationSelection formulationSelectionFrom(FormulationMapping formulationMapping, PKSimProject project) - { - var formulation = project.BuildingBlockById(formulationMapping.TemplateFormulationId) ?? formulationMapping.Formulation; - return new FormulationSelection {Name = formulation.Name, Key = formulationMapping.FormulationKey}; - } + private FormulationSelection[] formulationMappingFrom(IReadOnlyList formulationMappings, PKSimProject project) + { + if (!formulationMappings.Any()) + return null; - public override async Task MapToModel(SnapshotCompoundProperties snapshot, SnapshotContextWithSimulation snapshotContext) - { - var simulation = snapshotContext.Simulation; - var compoundProperties = simulation.CompoundPropertiesFor(snapshot.Name); - var simulationSubject = simulation.BuildingBlock(); + return formulationMappings + .Select(x => formulationSelectionFrom(x, project)) + .ToArray(); + } - await _calculationMethodCacheMapper.MapToModel(snapshot.CalculationMethods, new CalculationMethodCacheSnapshotContext(compoundProperties.CalculationMethodCache, snapshotContext)); - updateAlternativeSelections(snapshot.Alternatives, compoundProperties); - compoundProperties.Processes = await modelProcessSelectionFrom(snapshot.Processes, compoundProperties.Compound, simulationSubject, snapshotContext); - compoundProperties.ProtocolProperties = modelProtocolPropertiesFrom(snapshot.Protocol, snapshotContext.Project); + private FormulationSelection formulationSelectionFrom(FormulationMapping formulationMapping, PKSimProject project) + { + var formulation = project.BuildingBlockById(formulationMapping.TemplateFormulationId) ?? formulationMapping.Formulation; + return new FormulationSelection { Name = formulation.Name, Key = formulationMapping.FormulationKey }; + } - return compoundProperties; - } + public override async Task MapToModel(SnapshotCompoundProperties snapshot, SnapshotContextWithSimulation snapshotContext) + { + var simulation = snapshotContext.Simulation; + var compoundProperties = simulation.CompoundPropertiesFor(snapshot.Name); + var simulationSubject = simulation.BuildingBlock(); - private ProtocolProperties modelProtocolPropertiesFrom(ProtocolSelection snapshotProtocol, PKSimProject project) - { - var protocolProperties = new ProtocolProperties(); - if (snapshotProtocol == null) - return protocolProperties; + await _calculationMethodCacheMapper.MapToModel(snapshot.CalculationMethods, new CalculationMethodCacheSnapshotContext(compoundProperties.CalculationMethodCache, snapshotContext)); + updateAlternativeSelections(snapshot.Alternatives, compoundProperties); + compoundProperties.Processes = await modelProcessSelectionFrom(snapshot.Processes, compoundProperties.Compound, simulationSubject, snapshotContext); + compoundProperties.ProtocolProperties = modelProtocolPropertiesFrom(snapshot.Protocol, snapshotContext.Project); - var protocol = project.BuildingBlockByName(snapshotProtocol.Name); - protocolProperties.Protocol = protocol; - updateFormulationMapping(protocolProperties, snapshotProtocol.Formulations, project); + return compoundProperties; + } + + private ProtocolProperties modelProtocolPropertiesFrom(ProtocolSelection snapshotProtocol, PKSimProject project) + { + var protocolProperties = new ProtocolProperties(); + if (snapshotProtocol == null) return protocolProperties; - } - private void updateFormulationMapping(ProtocolProperties protocolProperties, FormulationSelection[] snapshotProtocolFormulations, PKSimProject project) - { - snapshotProtocolFormulations?.Each(x => - { - var formulation = project.BuildingBlockByName(x.Name); - var formulationMapping = new FormulationMapping - { - Formulation = formulation, - FormulationKey = x.Key, - TemplateFormulationId = formulation.Id - }; - protocolProperties.AddFormulationMapping(formulationMapping); - }); - } + var protocol = project.BuildingBlockByName(snapshotProtocol.Name); + protocolProperties.Protocol = protocol; + updateFormulationMapping(protocolProperties, snapshotProtocol.Formulations, project); + return protocolProperties; + } - private async Task modelProcessSelectionFrom(CompoundProcessSelection[] snapshotProcesses, Model.Compound compound, ISimulationSubject simulationSubject, SnapshotContext snapshotContext) + private void updateFormulationMapping(ProtocolProperties protocolProperties, FormulationSelection[] snapshotProtocolFormulations, PKSimProject project) + { + snapshotProtocolFormulations?.Each(x => { - var compoundProcessesSelection = new CompoundProcessesSelection(); - if (snapshotProcesses == null) - return compoundProcessesSelection; - - foreach (var snapshotProcess in snapshotProcesses) + var formulation = project.BuildingBlockByName(x.Name); + var formulationMapping = new FormulationMapping { - var process = compound.ProcessByName(snapshotProcess.Name) ?? notSelectedProcessFrom(snapshotProcess, simulationSubject); - if (process == null) - { - //No process found and a name was specified. This is a snapshot that is corrupted - if(!string.IsNullOrEmpty(snapshotProcess.Name)) - _logger.AddWarning(PKSimConstants.Error.ProcessNotFoundInCompound(snapshotProcess.Name, compound.Name)); + Formulation = formulation, + FormulationKey = x.Key, + TemplateFormulationId = formulation.Id + }; + protocolProperties.AddFormulationMapping(formulationMapping); + }); + } - continue; + private async Task modelProcessSelectionFrom(CompoundProcessSelection[] snapshotProcesses, Model.Compound compound, ISimulationSubject simulationSubject, SnapshotContext snapshotContext) + { + var compoundProcessesSelection = new CompoundProcessesSelection(); + if (snapshotProcesses == null) + return compoundProcessesSelection; - } + foreach (var snapshotProcess in snapshotProcesses) + { + var process = compound.ProcessByName(snapshotProcess.Name) ?? notSelectedProcessFrom(snapshotProcess, simulationSubject); + if (process == null) + { + //No process found and a name was specified. This is a snapshot that is corrupted + if (!string.IsNullOrEmpty(snapshotProcess.Name)) + _logger.AddWarning(PKSimConstants.Error.ProcessNotFoundInCompound(snapshotProcess.Name, compound.Name)); - await addProcessToProcessSelection(compoundProcessesSelection, snapshotProcess, process, snapshotContext); + continue; } - return compoundProcessesSelection; - } - - private async Task addProcessToProcessSelection(CompoundProcessesSelection compoundProcessesSelection, CompoundProcessSelection snapshotCompoundProcessSelection, Model.CompoundProcess process, SnapshotContext snapshotContext) - { - var processSelectionGroup = selectionGroupFor(compoundProcessesSelection, process); - var processContext = new CompoundProcessSnapshotContext(process, snapshotContext); - var processSelection = await _processMappingMapper.MapToModel(snapshotCompoundProcessSelection, processContext); - processSelectionGroup.AddProcessSelection(processSelection); + await addProcessToProcessSelection(compoundProcessesSelection, snapshotProcess, process, snapshotContext); } - private Model.CompoundProcess notSelectedProcessFrom(CompoundProcessSelection snapshotCompoundProcessSelection, ISimulationSubject simulationSubject) - { - //Partial process - var moleculeName = snapshotCompoundProcessSelection.MoleculeName; - var systemicProcessType = snapshotCompoundProcessSelection.SystemicProcessType; + return compoundProcessesSelection; + } - //this should be a specific process - if (!string.IsNullOrEmpty(systemicProcessType)) - return new NotSelectedSystemicProcess {SystemicProcessType = SystemicProcessTypes.ById(systemicProcessType)}; + private async Task addProcessToProcessSelection(CompoundProcessesSelection compoundProcessesSelection, CompoundProcessSelection snapshotCompoundProcessSelection, Model.CompoundProcess process, SnapshotContext snapshotContext) + { + var processSelectionGroup = selectionGroupFor(compoundProcessesSelection, process); + var processContext = new CompoundProcessSnapshotContext(process, snapshotContext); + var processSelection = await _processMappingMapper.MapToModel(snapshotCompoundProcessSelection, processContext); + processSelectionGroup.AddProcessSelection(processSelection); + } - if (string.IsNullOrEmpty(moleculeName)) - return null; + private Model.CompoundProcess notSelectedProcessFrom(CompoundProcessSelection snapshotCompoundProcessSelection, ISimulationSubject simulationSubject) + { + //Partial process + var moleculeName = snapshotCompoundProcessSelection.MoleculeName; + var systemicProcessType = snapshotCompoundProcessSelection.SystemicProcessType; - var molecule = simulationSubject.MoleculeByName(moleculeName); - if (molecule == null) - return null; + //this should be a specific process + if (!string.IsNullOrEmpty(systemicProcessType)) + return new NotSelectedSystemicProcess { SystemicProcessType = SystemicProcessTypes.ById(systemicProcessType) }; - switch (molecule) - { - case IndividualTransporter _: - return new TransportPartialProcess {MoleculeName = moleculeName}; - case IndividualEnzyme _: - return new EnzymaticProcess {MoleculeName = moleculeName}; - case IndividualOtherProtein _: - return new SpecificBindingPartialProcess {MoleculeName = moleculeName}; - } + if (string.IsNullOrEmpty(moleculeName)) + return null; + var molecule = simulationSubject.MoleculeByName(moleculeName); + if (molecule == null) return null; - } - private ProcessSelectionGroup selectionGroupFor(CompoundProcessesSelection compoundProcessesSelection, Model.CompoundProcess process) + switch (molecule) { - return selectionGroup(compoundProcessesSelection.MetabolizationSelection, process, SystemicProcessTypes.Hepatic) ?? - selectionGroup(compoundProcessesSelection.TransportAndExcretionSelection, process, SystemicProcessTypes.GFR, SystemicProcessTypes.Biliary, SystemicProcessTypes.Renal) ?? - selectionGroup(compoundProcessesSelection.SpecificBindingSelection, process); + case IndividualTransporter _: + return new TransportPartialProcess { MoleculeName = moleculeName }; + case IndividualEnzyme _: + return new EnzymaticProcess { MoleculeName = moleculeName }; + case IndividualOtherProtein _: + return new SpecificBindingPartialProcess { MoleculeName = moleculeName }; } - private ProcessSelectionGroup selectionGroup(ProcessSelectionGroup processSelectionGroup, Model.CompoundProcess process, params SystemicProcessType[] systemicProcessTypes) where TPartialProcess : PartialProcess - { - if (process.IsAnImplementationOf()) - return processSelectionGroup; + return null; + } - var systemicProcess = process as SystemicProcess; - if (systemicProcess == null) - return null; + private ProcessSelectionGroup selectionGroupFor(CompoundProcessesSelection compoundProcessesSelection, Model.CompoundProcess process) + { + return selectionGroup(compoundProcessesSelection.MetabolizationSelection, process, SystemicProcessTypes.Hepatic) ?? + selectionGroup(compoundProcessesSelection.TransportAndExcretionSelection, process, SystemicProcessTypes.GFR, SystemicProcessTypes.Biliary, SystemicProcessTypes.Renal) ?? + selectionGroup(compoundProcessesSelection.SpecificBindingSelection, process); + } - if (systemicProcess.SystemicProcessType.IsOneOf(systemicProcessTypes)) - return processSelectionGroup; + private ProcessSelectionGroup selectionGroup(ProcessSelectionGroup processSelectionGroup, Model.CompoundProcess process, params SystemicProcessType[] systemicProcessTypes) where TPartialProcess : PartialProcess + { + if (process.IsAnImplementationOf()) + return processSelectionGroup; + var systemicProcess = process as SystemicProcess; + if (systemicProcess == null) return null; - } - private void updateAlternativeSelections(CompoundGroupSelection[] snapshotAlternatives, ModelCompoundProperties compoundProperties) + if (systemicProcess.SystemicProcessType.IsOneOf(systemicProcessTypes)) + return processSelectionGroup; + + return null; + } + + private void updateAlternativeSelections(CompoundGroupSelection[] snapshotAlternatives, ModelCompoundProperties compoundProperties) + { + snapshotAlternatives?.Each(x => updateAlternativeSelection(x, compoundProperties)); + } + + private void updateAlternativeSelection(CompoundGroupSelection snapshotCompoundGroupSelection, ModelCompoundProperties compoundProperties) + { + var compoundGroupSelection = compoundProperties.CompoundGroupSelections.Find(x => x.GroupName == snapshotCompoundGroupSelection.GroupName); + if (compoundGroupSelection == null) { - snapshotAlternatives?.Each(x => updateAlternativeSelection(x, compoundProperties)); + _logger.AddError(PKSimConstants.Error.CompoundGroupNotFoundFor(snapshotCompoundGroupSelection.GroupName, compoundProperties.Compound.Name)); + return; } - private void updateAlternativeSelection(CompoundGroupSelection snapshotCompoundGroupSelection, ModelCompoundProperties compoundProperties) + var alternativeGroup = compoundProperties.Compound.ParameterAlternativeGroup(snapshotCompoundGroupSelection.GroupName); + if (alternativeGroup == null) { - var compoundGroupSelection = compoundProperties.CompoundGroupSelections.Find(x => x.GroupName == snapshotCompoundGroupSelection.GroupName); - if (compoundGroupSelection == null) - { - _logger.AddError(PKSimConstants.Error.CompoundGroupNotFoundFor(snapshotCompoundGroupSelection.GroupName, compoundProperties.Compound.Name)); - return; - } - - var alternativeGroup = compoundProperties.Compound.ParameterAlternativeGroup(snapshotCompoundGroupSelection.GroupName); - if (alternativeGroup == null) - { - _logger.AddError(PKSimConstants.Error.CompoundGroupNotFoundFor(snapshotCompoundGroupSelection.GroupName, compoundProperties.Compound.Name)); - return; - } - - var alternative = alternativeGroup.AlternativeByName(snapshotCompoundGroupSelection.AlternativeName); - if (alternative == null) - { - _logger.AddError(PKSimConstants.Error.CompoundAlternativeNotFoundFor(snapshotCompoundGroupSelection.AlternativeName, alternativeGroup.DefaultAlternative?.Name, snapshotCompoundGroupSelection.GroupName, compoundProperties.Compound.Name)); - return; - } + _logger.AddError(PKSimConstants.Error.CompoundGroupNotFoundFor(snapshotCompoundGroupSelection.GroupName, compoundProperties.Compound.Name)); + return; + } - compoundGroupSelection.AlternativeName = snapshotCompoundGroupSelection.AlternativeName; + var alternative = alternativeGroup.AlternativeByName(snapshotCompoundGroupSelection.AlternativeName); + if (alternative == null) + { + _logger.AddError(PKSimConstants.Error.CompoundAlternativeNotFoundFor(snapshotCompoundGroupSelection.AlternativeName, alternativeGroup.DefaultAlternative?.Name, snapshotCompoundGroupSelection.GroupName, compoundProperties.Compound.Name)); + return; } + + compoundGroupSelection.AlternativeName = snapshotCompoundGroupSelection.AlternativeName; } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/CurveChartMapper.cs b/src/PKSim.Core/Snapshots/Mappers/CurveChartMapper.cs index 1e973005f..2683da7f5 100644 --- a/src/PKSim.Core/Snapshots/Mappers/CurveChartMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/CurveChartMapper.cs @@ -3,80 +3,81 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Services; +using OSPSuite.Core.Extensions; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Core.Chart; using ModelCurveChart = OSPSuite.Core.Chart.CurveChart; using SnapshotCurveChart = PKSim.Core.Snapshots.CurveChart; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public abstract class CurveChartMapper : ObjectBaseSnapshotMapperBase where TCurveChart : ModelCurveChart { - public abstract class CurveChartMapper : ObjectBaseSnapshotMapperBase where TCurveChart : ModelCurveChart - { - private readonly ChartMapper _chartMapper; - private readonly AxisMapper _axisMapper; - private readonly CurveMapper _curveMapper; - private readonly IIdGenerator _idGenerator; - public Func ChartFactoryFunc { get; set; } + private readonly ChartMapper _chartMapper; + private readonly AxisMapper _axisMapper; + private readonly CurveMapper _curveMapper; + private readonly IIdGenerator _idGenerator; + public Func ChartFactoryFunc { get; set; } - protected CurveChartMapper(ChartMapper chartMapper, AxisMapper axisMapper, CurveMapper curveMapper, IIdGenerator idGenerator) - { - _chartMapper = chartMapper; - _axisMapper = axisMapper; - _curveMapper = curveMapper; - _idGenerator = idGenerator; - } + protected CurveChartMapper(ChartMapper chartMapper, AxisMapper axisMapper, CurveMapper curveMapper, IIdGenerator idGenerator) + { + _chartMapper = chartMapper; + _axisMapper = axisMapper; + _curveMapper = curveMapper; + _idGenerator = idGenerator; + } - public override async Task MapToSnapshot(TCurveChart curveChart) - { - var snapshot = await SnapshotFrom(curveChart); - await _chartMapper.MapToSnapshot(curveChart, snapshot); - snapshot.Axes = await _axisMapper.MapToSnapshots(curveChart.Axes); - snapshot.Curves = await _curveMapper.MapToSnapshots(curveChart.Curves); - return snapshot; - } + public override async Task MapToSnapshot(TCurveChart curveChart) + { + var snapshot = await SnapshotFrom(curveChart); + await _chartMapper.MapToSnapshot(curveChart, snapshot); + snapshot.Axes = await _axisMapper.MapToSnapshots(curveChart.Axes); + snapshot.Curves = await _curveMapper.MapToSnapshots(curveChart.Curves); + return snapshot; + } - public override async Task MapToModel(SnapshotCurveChart snapshot, SimulationAnalysisContext simulationAnalysisContext) - { - var curveChart = ChartFactoryFunc().WithId(_idGenerator.NewId()); - MapSnapshotPropertiesToModel(snapshot, curveChart); - await _chartMapper.MapToModel(snapshot, new ChartSnapshotContext(curveChart, simulationAnalysisContext)); - await updateChartAxes(curveChart, snapshot.Axes, simulationAnalysisContext); - await updateChartCurves(curveChart, snapshot.Curves, simulationAnalysisContext); - return curveChart; - } + public override async Task MapToModel(SnapshotCurveChart snapshot, SimulationAnalysisContext simulationAnalysisContext) + { + var curveChart = ChartFactoryFunc().WithId(_idGenerator.NewId()); + MapSnapshotPropertiesToModel(snapshot, curveChart); + await _chartMapper.MapToModel(snapshot, new ChartSnapshotContext(curveChart, simulationAnalysisContext)); + await updateChartAxes(curveChart, snapshot.Axes, simulationAnalysisContext); + await updateChartCurves(curveChart, snapshot.Curves, simulationAnalysisContext); + return curveChart; + } - private async Task updateChartAxes(ModelCurveChart curveChart, IReadOnlyList snapshotAxes, SnapshotContext snapshotContext) - { - var axes = await _axisMapper.MapToModels(snapshotAxes, snapshotContext); - axes?.Each(curveChart.AddAxis); - } + private async Task updateChartAxes(ModelCurveChart curveChart, IReadOnlyList snapshotAxes, SnapshotContext snapshotContext) + { + var axes = await _axisMapper.MapToModels(snapshotAxes, snapshotContext); + axes?.Each(curveChart.AddAxis); + } - private async Task updateChartCurves(ModelCurveChart curveChart, IReadOnlyList snapshotCurves, SimulationAnalysisContext simulationAnalysisContext) - { - var curves = await _curveMapper.MapToModels(snapshotCurves, simulationAnalysisContext); - curves?.Each(x => curveChart.AddCurve(x, useAxisDefault: false)); - } + private async Task updateChartCurves(ModelCurveChart curveChart, IReadOnlyList snapshotCurves, SimulationAnalysisContext simulationAnalysisContext) + { + var curves = await _curveMapper.MapToModels(snapshotCurves, simulationAnalysisContext); + curves?.Each(x => curveChart.AddCurve(x, useAxisDefault: false)); } +} - public abstract class NewableCurveChartMapper : CurveChartMapper where TCurveChart : ModelCurveChart, new() +public abstract class NewableCurveChartMapper : CurveChartMapper where TCurveChart : ModelCurveChart, new() +{ + protected NewableCurveChartMapper(ChartMapper chartMapper, AxisMapper axisMapper, CurveMapper curveMapper, IIdGenerator idGenerator) : base(chartMapper, axisMapper, curveMapper, idGenerator) { - protected NewableCurveChartMapper(ChartMapper chartMapper, AxisMapper axisMapper, CurveMapper curveMapper, IIdGenerator idGenerator) : base(chartMapper, axisMapper, curveMapper, idGenerator) - { - ChartFactoryFunc = () => new TCurveChart(); - } + ChartFactoryFunc = () => new TCurveChart(); } +} - public class SimulationTimeProfileChartMapper : NewableCurveChartMapper +public class SimulationTimeProfileChartMapper : NewableCurveChartMapper +{ + public SimulationTimeProfileChartMapper(ChartMapper chartMapper, AxisMapper axisMapper, CurveMapper curveMapper, IIdGenerator idGenerator) : base(chartMapper, axisMapper, curveMapper, idGenerator) { - public SimulationTimeProfileChartMapper(ChartMapper chartMapper, AxisMapper axisMapper, CurveMapper curveMapper, IIdGenerator idGenerator) : base(chartMapper, axisMapper, curveMapper, idGenerator) - { - } } +} - public class IndividualSimulationComparisonMapper : NewableCurveChartMapper +public class IndividualSimulationComparisonMapper : NewableCurveChartMapper +{ + public IndividualSimulationComparisonMapper(ChartMapper chartMapper, AxisMapper axisMapper, CurveMapper curveMapper, IIdGenerator idGenerator) : base(chartMapper, axisMapper, curveMapper, idGenerator) { - public IndividualSimulationComparisonMapper(ChartMapper chartMapper, AxisMapper axisMapper, CurveMapper curveMapper, IIdGenerator idGenerator) : base(chartMapper, axisMapper, curveMapper, idGenerator) - { - } } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/CurveMapper.cs b/src/PKSim.Core/Snapshots/Mappers/CurveMapper.cs index fc6e32648..755d79328 100644 --- a/src/PKSim.Core/Snapshots/Mappers/CurveMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/CurveMapper.cs @@ -3,76 +3,76 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain.UnitSystem; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Assets; using SnapshotCurve = PKSim.Core.Snapshots.Curve; using ModelCurve = OSPSuite.Core.Chart.Curve; using ModelDataRepository = OSPSuite.Core.Domain.Data.DataRepository; using ModelDataColumn = OSPSuite.Core.Domain.Data.DataColumn; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class CurveMapper : SnapshotMapperBase { - public class CurveMapper : SnapshotMapperBase + private readonly CurveOptionsMapper _curveOptionsMapper; + private readonly IDimensionFactory _dimensionFactory; + private readonly IOSPSuiteLogger _logger; + + public CurveMapper(CurveOptionsMapper curveOptionsMapper, IDimensionFactory dimensionFactory, IOSPSuiteLogger logger) { - private readonly CurveOptionsMapper _curveOptionsMapper; - private readonly IDimensionFactory _dimensionFactory; - private readonly IOSPSuiteLogger _logger; + _curveOptionsMapper = curveOptionsMapper; + _dimensionFactory = dimensionFactory; + _logger = logger; + } - public CurveMapper(CurveOptionsMapper curveOptionsMapper, IDimensionFactory dimensionFactory, IOSPSuiteLogger logger) + public override async Task MapToSnapshot(ModelCurve curve) + { + var snapshot = await SnapshotFrom(curve, x => { - _curveOptionsMapper = curveOptionsMapper; - _dimensionFactory = dimensionFactory; - _logger = logger; - } + x.Name = SnapshotValueFor(curve.Name); + x.X = curve.xData?.PathAsString; + x.Y = curve.yData?.PathAsString; + }); + snapshot.CurveOptions = await _curveOptionsMapper.MapToSnapshot(curve.CurveOptions); + return snapshot; + } - public override async Task MapToSnapshot(ModelCurve curve) - { - var snapshot = await SnapshotFrom(curve, x => - { - x.Name = SnapshotValueFor(curve.Name); - x.X = curve.xData?.PathAsString; - x.Y = curve.yData?.PathAsString; - }); - snapshot.CurveOptions = await _curveOptionsMapper.MapToSnapshot(curve.CurveOptions); - return snapshot; - } + public override async Task MapToModel(SnapshotCurve snapshot, SimulationAnalysisContext simulationAnalysisContext) + { + var curve = new ModelCurve { Name = snapshot.Name }; + var curveOptions = await _curveOptionsMapper.MapToModel(snapshot.CurveOptions, simulationAnalysisContext); + curve.CurveOptions.UpdateFrom(curveOptions); - public override async Task MapToModel(SnapshotCurve snapshot, SimulationAnalysisContext simulationAnalysisContext) + var yData = findCurveWithPath(snapshot.Y, simulationAnalysisContext.DataRepositories); + if (yData == null) { - var curve = new ModelCurve {Name = snapshot.Name}; - var curveOptions = await _curveOptionsMapper.MapToModel(snapshot.CurveOptions, simulationAnalysisContext); - curve.CurveOptions.UpdateFrom(curveOptions); + //Only show a warning if the output were already calculated. Otherwise curves will not be generated + if (simulationAnalysisContext.RunSimulation) + _logger.AddWarning(PKSimConstants.Error.CouldNotFindQuantityWithPath(snapshot.Y)); - var yData = findCurveWithPath(snapshot.Y, simulationAnalysisContext.DataRepositories); - if (yData == null) - { - //Only show a warning if the output were already calculated. Otherwise curves will not be generated - if (simulationAnalysisContext.RunSimulation) - _logger.AddWarning(PKSimConstants.Error.CouldNotFindQuantityWithPath(snapshot.Y)); - - return null; - } + return null; + } - curve.SetyData(yData, _dimensionFactory); + curve.SetyData(yData, _dimensionFactory); - ModelDataColumn xData = yData.BaseGrid; - if (!string.Equals(snapshot.X, xData?.Name)) - xData = findCurveWithPath(snapshot.X, simulationAnalysisContext.DataRepositories); + ModelDataColumn xData = yData.BaseGrid; + if (!string.Equals(snapshot.X, xData?.Name)) + xData = findCurveWithPath(snapshot.X, simulationAnalysisContext.DataRepositories); - if (xData == null) - { - if (simulationAnalysisContext.RunSimulation) - _logger.AddWarning(PKSimConstants.Error.CouldNotFindQuantityWithPath(snapshot.X)); - - return null; - } + if (xData == null) + { + if (simulationAnalysisContext.RunSimulation) + _logger.AddWarning(PKSimConstants.Error.CouldNotFindQuantityWithPath(snapshot.X)); - curve.SetxData(xData, _dimensionFactory); - return curve; + return null; } - private ModelDataColumn findCurveWithPath(string path, IReadOnlyList dataRepositories) - { - return dataRepositories.SelectMany(x => x.Columns).FirstOrDefault(x => string.Equals(x.QuantityInfo.PathAsString, path)); - } + curve.SetxData(xData, _dimensionFactory); + return curve; + } + + private ModelDataColumn findCurveWithPath(string path, IReadOnlyList dataRepositories) + { + return dataRepositories.SelectMany(x => x.Columns).FirstOrDefault(x => string.Equals(x.QuantityInfo.PathAsString, path)); } -} +} \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/CurveOptionsMapper.cs b/src/PKSim.Core/Snapshots/Mappers/CurveOptionsMapper.cs index 0bcbbee3d..54cff5042 100644 --- a/src/PKSim.Core/Snapshots/Mappers/CurveOptionsMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/CurveOptionsMapper.cs @@ -1,51 +1,45 @@ using System.Threading.Tasks; -using NPOI.HSSF.Record.Chart; +using OSPSuite.Core.Snapshots.Mappers; using ModelCurveOptions = OSPSuite.Core.Chart.CurveOptions; using SnapshotCurveOptions = PKSim.Core.Snapshots.CurveOptions; -namespace PKSim.Core.Snapshots.Mappers -{ - public class CurveOptionsMapper : SnapshotMapperBase - { - private readonly ModelCurveOptions _defaultCurveOption; +namespace PKSim.Core.Snapshots.Mappers; - public CurveOptionsMapper() - { - _defaultCurveOption = new ModelCurveOptions(); - } +public class CurveOptionsMapper : SnapshotMapperBase +{ + private readonly ModelCurveOptions _defaultCurveOption = new(); - public override Task MapToSnapshot(ModelCurveOptions curveOptions) + public override Task MapToSnapshot(ModelCurveOptions curveOptions) + { + return SnapshotFrom(curveOptions, x => { - return SnapshotFrom(curveOptions, x => - { - x.Visible = SnapshotValueFor(curveOptions.Visible, _defaultCurveOption.Visible); - x.ShouldShowLLOQ = SnapshotValueFor(curveOptions.ShouldShowLLOQ, _defaultCurveOption.ShouldShowLLOQ); - x.VisibleInLegend = SnapshotValueFor(curveOptions.VisibleInLegend, _defaultCurveOption.VisibleInLegend); - x.InterpolationMode = SnapshotValueFor(curveOptions.InterpolationMode, _defaultCurveOption.InterpolationMode); - x.Color = SnapshotValueFor(curveOptions.Color, _defaultCurveOption.Color); - x.LegendIndex = curveOptions.LegendIndex; - x.LineThickness = SnapshotValueFor(curveOptions.LineThickness, _defaultCurveOption.LineThickness); - x.LineStyle = SnapshotValueFor(curveOptions.LineStyle, _defaultCurveOption.LineStyle); - x.Symbol = SnapshotValueFor(curveOptions.Symbol, _defaultCurveOption.Symbol); - x.yAxisType = SnapshotValueFor(curveOptions.yAxisType, _defaultCurveOption.yAxisType); - }); - } + x.Visible = SnapshotValueFor(curveOptions.Visible, _defaultCurveOption.Visible); + x.ShouldShowLLOQ = SnapshotValueFor(curveOptions.ShouldShowLLOQ, _defaultCurveOption.ShouldShowLLOQ); + x.VisibleInLegend = SnapshotValueFor(curveOptions.VisibleInLegend, _defaultCurveOption.VisibleInLegend); + x.InterpolationMode = SnapshotValueFor(curveOptions.InterpolationMode, _defaultCurveOption.InterpolationMode); + x.Color = SnapshotValueFor(curveOptions.Color, _defaultCurveOption.Color); + x.LegendIndex = curveOptions.LegendIndex; + x.LineThickness = SnapshotValueFor(curveOptions.LineThickness, _defaultCurveOption.LineThickness); + x.LineStyle = SnapshotValueFor(curveOptions.LineStyle, _defaultCurveOption.LineStyle); + x.Symbol = SnapshotValueFor(curveOptions.Symbol, _defaultCurveOption.Symbol); + x.yAxisType = SnapshotValueFor(curveOptions.yAxisType, _defaultCurveOption.yAxisType); + }); + } - public override Task MapToModel(SnapshotCurveOptions snapshot, SnapshotContext snapshotContext) + public override Task MapToModel(SnapshotCurveOptions snapshot, SnapshotContext snapshotContext) + { + return Task.FromResult(new ModelCurveOptions { - return Task.FromResult(new ModelCurveOptions - { - Visible = ModelValueFor(snapshot.Visible, _defaultCurveOption.Visible), - ShouldShowLLOQ = ModelValueFor(snapshot.ShouldShowLLOQ, _defaultCurveOption.ShouldShowLLOQ), - VisibleInLegend = ModelValueFor(snapshot.VisibleInLegend, _defaultCurveOption.VisibleInLegend), - InterpolationMode = ModelValueFor(snapshot.InterpolationMode, _defaultCurveOption.InterpolationMode), - Color = ModelValueFor(snapshot.Color, _defaultCurveOption.Color), - LegendIndex = snapshot.LegendIndex, - LineThickness = ModelValueFor(snapshot.LineThickness, _defaultCurveOption.LineThickness), - LineStyle = ModelValueFor(snapshot.LineStyle, _defaultCurveOption.LineStyle), - Symbol = ModelValueFor(snapshot.Symbol, _defaultCurveOption.Symbol), - yAxisType = ModelValueFor(snapshot.yAxisType, _defaultCurveOption.yAxisType), - }); - } + Visible = ModelValueFor(snapshot.Visible, _defaultCurveOption.Visible), + ShouldShowLLOQ = ModelValueFor(snapshot.ShouldShowLLOQ, _defaultCurveOption.ShouldShowLLOQ), + VisibleInLegend = ModelValueFor(snapshot.VisibleInLegend, _defaultCurveOption.VisibleInLegend), + InterpolationMode = ModelValueFor(snapshot.InterpolationMode, _defaultCurveOption.InterpolationMode), + Color = ModelValueFor(snapshot.Color, _defaultCurveOption.Color), + LegendIndex = snapshot.LegendIndex, + LineThickness = ModelValueFor(snapshot.LineThickness, _defaultCurveOption.LineThickness), + LineStyle = ModelValueFor(snapshot.LineStyle, _defaultCurveOption.LineStyle), + Symbol = ModelValueFor(snapshot.Symbol, _defaultCurveOption.Symbol), + yAxisType = ModelValueFor(snapshot.yAxisType, _defaultCurveOption.yAxisType), + }); } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/DataColumnMapper.cs b/src/PKSim.Core/Snapshots/Mappers/DataColumnMapper.cs index 81dbad788..5a12fa840 100644 --- a/src/PKSim.Core/Snapshots/Mappers/DataColumnMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/DataColumnMapper.cs @@ -4,89 +4,90 @@ using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Data; using OSPSuite.Core.Domain.UnitSystem; +using OSPSuite.Core.Extensions; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Core.Repositories; using SnapshotDataColumn = PKSim.Core.Snapshots.DataColumn; using ModelDataColumn = OSPSuite.Core.Domain.Data.DataColumn; using ModelDataRepository = OSPSuite.Core.Domain.Data.DataRepository; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class SnapshotContextWithDataRepository : SnapshotContext { - public class SnapshotContextWithDataRepository : SnapshotContext - { - public ModelDataRepository DataRepository { get; } + public ModelDataRepository DataRepository { get; } - public SnapshotContextWithDataRepository(ModelDataRepository dataRepository, SnapshotContext baseContext) : base(baseContext) - { - DataRepository = dataRepository; - } + public SnapshotContextWithDataRepository(ModelDataRepository dataRepository, SnapshotContext baseContext) : base(baseContext) + { + DataRepository = dataRepository; } +} - public class DataColumnMapper : SnapshotMapperBase - { - private readonly DataInfoMapper _dataInfoMapper; - private readonly QuantityInfoMapper _quantityInfoMapper; - private readonly IDimensionRepository _dimensionRepository; +public class DataColumnMapper : SnapshotMapperBase +{ + private readonly DataInfoMapper _dataInfoMapper; + private readonly QuantityInfoMapper _quantityInfoMapper; + private readonly IDimensionRepository _dimensionRepository; - public DataColumnMapper(DataInfoMapper dataInfoMapper, QuantityInfoMapper quantityInfoMapper, IDimensionRepository dimensionRepository) - { - _dataInfoMapper = dataInfoMapper; - _quantityInfoMapper = quantityInfoMapper; - _dimensionRepository = dimensionRepository; - } + public DataColumnMapper(DataInfoMapper dataInfoMapper, QuantityInfoMapper quantityInfoMapper, IDimensionRepository dimensionRepository) + { + _dataInfoMapper = dataInfoMapper; + _quantityInfoMapper = quantityInfoMapper; + _dimensionRepository = dimensionRepository; + } - public override async Task MapToSnapshot(ModelDataColumn dataColumn) + public override async Task MapToSnapshot(ModelDataColumn dataColumn) + { + var snapshot = await SnapshotFrom(dataColumn, x => { - var snapshot = await SnapshotFrom(dataColumn, x => - { - x.Name = dataColumn.Name; - x.Values = valuesInDisplayUnits(dataColumn); - x.Dimension = dataColumn.Dimension.Name; - x.Unit = SnapshotValueFor(dataColumn.DisplayUnit.Name); - }); + x.Name = dataColumn.Name; + x.Values = valuesInDisplayUnits(dataColumn); + x.Dimension = dataColumn.Dimension.Name; + x.Unit = SnapshotValueFor(dataColumn.DisplayUnit.Name); + }); - snapshot.RelatedColumns = await this.MapToSnapshots(dataColumn.RelatedColumns); - snapshot.DataInfo = await _dataInfoMapper.MapToSnapshot(dataColumn.DataInfo); - snapshot.QuantityInfo = await _quantityInfoMapper.MapToSnapshot(dataColumn.QuantityInfo); - return snapshot; - } + snapshot.RelatedColumns = await this.MapToSnapshots(dataColumn.RelatedColumns); + snapshot.DataInfo = await _dataInfoMapper.MapToSnapshot(dataColumn.DataInfo); + snapshot.QuantityInfo = await _quantityInfoMapper.MapToSnapshot(dataColumn.QuantityInfo); + return snapshot; + } - private IReadOnlyList valuesInBaseUnits(ModelDataColumn dataColumn, IEnumerable valuesInDisplayUnits) - { - return dataColumn.ConvertToBaseValues(valuesInDisplayUnits); - } + private IReadOnlyList valuesInBaseUnits(ModelDataColumn dataColumn, IEnumerable valuesInDisplayUnits) + { + return dataColumn.ConvertToBaseValues(valuesInDisplayUnits); + } - private List valuesInDisplayUnits(ModelDataColumn dataColumn) - { - return dataColumn.ConvertToDisplayValues(dataColumn.Values).ToList(); - } + private List valuesInDisplayUnits(ModelDataColumn dataColumn) + { + return dataColumn.ConvertToDisplayValues(dataColumn.Values).ToList(); + } - public override async Task MapToModel(SnapshotDataColumn snapshot, SnapshotContextWithDataRepository snapshotContext) - { - var dataRepository = snapshotContext.DataRepository; - var dataInfo = await _dataInfoMapper.MapToModel(snapshot.DataInfo, snapshotContext); - var dimension = dimensionFrom(snapshot); - var dataColumn = dataInfo.Origin == ColumnOrigins.BaseGrid ? new BaseGrid(snapshot.Name, dimension) : new ModelDataColumn(snapshot.Name, dimension, dataRepository.BaseGrid); - //this needs to be set after DATA Info to be sure that we are using the value from the snapshot - dataColumn.DataInfo = dataInfo; - dataColumn.DisplayUnit = displayUnitFor(dimension, snapshot.Unit); - dataColumn.Values = valuesInBaseUnits(dataColumn, snapshot.Values); - dataColumn.QuantityInfo = await _quantityInfoMapper.MapToModel(snapshot.QuantityInfo, snapshotContext); + public override async Task MapToModel(SnapshotDataColumn snapshot, SnapshotContextWithDataRepository snapshotContext) + { + var dataRepository = snapshotContext.DataRepository; + var dataInfo = await _dataInfoMapper.MapToModel(snapshot.DataInfo, snapshotContext); + var dimension = dimensionFrom(snapshot); + var dataColumn = dataInfo.Origin == ColumnOrigins.BaseGrid ? new BaseGrid(snapshot.Name, dimension) : new ModelDataColumn(snapshot.Name, dimension, dataRepository.BaseGrid); + //this needs to be set after DATA Info to be sure that we are using the value from the snapshot + dataColumn.DataInfo = dataInfo; + dataColumn.DisplayUnit = displayUnitFor(dimension, snapshot.Unit); + dataColumn.Values = valuesInBaseUnits(dataColumn, snapshot.Values); + dataColumn.QuantityInfo = await _quantityInfoMapper.MapToModel(snapshot.QuantityInfo, snapshotContext); - var relatedColumns = await this.MapToModels(snapshot.RelatedColumns, snapshotContext); - relatedColumns?.Each(dataColumn.AddRelatedColumn); + var relatedColumns = await this.MapToModels(snapshot.RelatedColumns, snapshotContext); + relatedColumns?.Each(dataColumn.AddRelatedColumn); - return dataColumn; - } + return dataColumn; + } - private Unit displayUnitFor(IDimension dimension, string snapshotUnit) - { - return dimension.UnitOrDefault(snapshotUnit); - } + private Unit displayUnitFor(IDimension dimension, string snapshotUnit) + { + return dimension.UnitOrDefault(snapshotUnit); + } - private IDimension dimensionFrom(SnapshotDataColumn snapshot) - { - return _dimensionRepository.DimensionByName(snapshot.Dimension); - } + private IDimension dimensionFrom(SnapshotDataColumn snapshot) + { + return _dimensionRepository.DimensionByName(snapshot.Dimension); } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/DataInfoMapper.cs b/src/PKSim.Core/Snapshots/Mappers/DataInfoMapper.cs index 30cc44cac..0fbc011a0 100644 --- a/src/PKSim.Core/Snapshots/Mappers/DataInfoMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/DataInfoMapper.cs @@ -2,70 +2,70 @@ using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Data; using OSPSuite.Core.Domain.UnitSystem; +using OSPSuite.Core.Extensions; using OSPSuite.Utility.Extensions; using PKSim.Core.Repositories; using SnapshotDataInfo = PKSim.Core.Snapshots.DataInfo; using ModelDataInfo = OSPSuite.Core.Domain.Data.DataInfo; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class DataInfoMapper : SnapshotMapperBase { - public class DataInfoMapper : SnapshotMapperBase - { - private readonly ExtendedPropertyMapper _extendedPropertyMapper; - private readonly IDimension _molWeightDimension; + private readonly ExtendedPropertyMapper _extendedPropertyMapper; + private readonly IDimension _molWeightDimension; - public DataInfoMapper(ExtendedPropertyMapper extendedPropertyMapper, IDimensionRepository dimensionRepository) - { - _molWeightDimension = dimensionRepository.DimensionByName(Constants.Dimension.MOLECULAR_WEIGHT); - _extendedPropertyMapper = extendedPropertyMapper; - } + public DataInfoMapper(ExtendedPropertyMapper extendedPropertyMapper, IDimensionRepository dimensionRepository) + { + _molWeightDimension = dimensionRepository.DimensionByName(Constants.Dimension.MOLECULAR_WEIGHT); + _extendedPropertyMapper = extendedPropertyMapper; + } - public override async Task MapToSnapshot(ModelDataInfo dataInfo) + public override async Task MapToSnapshot(ModelDataInfo dataInfo) + { + var snapshot = await SnapshotFrom(dataInfo, x => { - var snapshot = await SnapshotFrom(dataInfo, x => - { - x.AuxiliaryType = dataInfo.AuxiliaryType; - x.Category = SnapshotValueFor(dataInfo.Category); - x.ComparisonThreshold = dataInfo.ComparisonThreshold; - x.LLOQ = dataInfo.LLOQ; - x.MolWeight = molWeightToDisplayValue(dataInfo); - x.Origin = SnapshotValueFor(dataInfo.Origin, ColumnOrigins.Undefined); - }); - snapshot.ExtendedProperties = await _extendedPropertyMapper.MapToSnapshots(dataInfo.ExtendedProperties); - return snapshot; - } + x.AuxiliaryType = dataInfo.AuxiliaryType; + x.Category = SnapshotValueFor(dataInfo.Category); + x.ComparisonThreshold = dataInfo.ComparisonThreshold; + x.LLOQ = dataInfo.LLOQ; + x.MolWeight = molWeightToDisplayValue(dataInfo); + x.Origin = SnapshotValueFor(dataInfo.Origin, ColumnOrigins.Undefined); + }); + snapshot.ExtendedProperties = await _extendedPropertyMapper.MapToSnapshots(dataInfo.ExtendedProperties); + return snapshot; + } - private double? molWeightToDisplayValue(ModelDataInfo dataInfo) - { - if (dataInfo.MolWeight != null) - return _molWeightDimension.BaseUnitValueToUnitValue(_molWeightDimension.DefaultUnit, dataInfo.MolWeight.Value); - return null; - } + private double? molWeightToDisplayValue(ModelDataInfo dataInfo) + { + if (dataInfo.MolWeight != null) + return _molWeightDimension.BaseUnitValueToUnitValue(_molWeightDimension.DefaultUnit, dataInfo.MolWeight.Value); + return null; + } - public override async Task MapToModel(SnapshotDataInfo snapshot, SnapshotContext snapshotContext) + public override async Task MapToModel(SnapshotDataInfo snapshot, SnapshotContext snapshotContext) + { + var origin = ModelValueFor(snapshot.Origin, ColumnOrigins.Undefined); + var dataInfo = new ModelDataInfo(origin) { - var origin = ModelValueFor(snapshot.Origin, ColumnOrigins.Undefined); - var dataInfo = new ModelDataInfo(origin) - { - AuxiliaryType = snapshot.AuxiliaryType, - Category = snapshot.Category, - ComparisonThreshold = snapshot.ComparisonThreshold, - LLOQ = snapshot.LLOQ, - MolWeight = molWeightToBaseValue(snapshot), - }; + AuxiliaryType = snapshot.AuxiliaryType, + Category = snapshot.Category, + ComparisonThreshold = snapshot.ComparisonThreshold, + LLOQ = snapshot.LLOQ, + MolWeight = molWeightToBaseValue(snapshot), + }; - var extendedProperties = await _extendedPropertyMapper.MapToModels(snapshot.ExtendedProperties, snapshotContext); - extendedProperties?.Each(dataInfo.ExtendedProperties.Add); + var extendedProperties = await _extendedPropertyMapper.MapToModels(snapshot.ExtendedProperties, snapshotContext); + extendedProperties?.Each(dataInfo.ExtendedProperties.Add); - return dataInfo; - } + return dataInfo; + } - private double? molWeightToBaseValue(SnapshotDataInfo snapshot) - { - if (snapshot.MolWeight == null) - return null; + private double? molWeightToBaseValue(SnapshotDataInfo snapshot) + { + if (snapshot.MolWeight == null) + return null; - return _molWeightDimension.UnitValueToBaseUnitValue(_molWeightDimension.DefaultUnit, snapshot.MolWeight.Value); - } + return _molWeightDimension.UnitValueToBaseUnitValue(_molWeightDimension.DefaultUnit, snapshot.MolWeight.Value); } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/DataRepositoryMapper.cs b/src/PKSim.Core/Snapshots/Mappers/DataRepositoryMapper.cs index 7d1072251..e01fcc2bb 100644 --- a/src/PKSim.Core/Snapshots/Mappers/DataRepositoryMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/DataRepositoryMapper.cs @@ -1,53 +1,53 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using OSPSuite.Core.Extensions; using OSPSuite.Utility.Extensions; using PKSim.Core.Extensions; using SnapshotDataRepository = PKSim.Core.Snapshots.DataRepository; using ModelDataRepository = OSPSuite.Core.Domain.Data.DataRepository; using ModelDataColumn = OSPSuite.Core.Domain.Data.DataColumn; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class DataRepositoryMapper : ObjectBaseSnapshotMapperBase { - public class DataRepositoryMapper : ObjectBaseSnapshotMapperBase + private readonly ExtendedPropertyMapper _extendedPropertyMapper; + private readonly DataColumnMapper _dataColumnMapper; + + public DataRepositoryMapper(ExtendedPropertyMapper extendedPropertyMapper, DataColumnMapper dataColumnMapper) + { + _extendedPropertyMapper = extendedPropertyMapper; + _dataColumnMapper = dataColumnMapper; + } + + public override async Task MapToSnapshot(ModelDataRepository dataRepository) { - private readonly ExtendedPropertyMapper _extendedPropertyMapper; - private readonly DataColumnMapper _dataColumnMapper; - - public DataRepositoryMapper(ExtendedPropertyMapper extendedPropertyMapper, DataColumnMapper dataColumnMapper) - { - _extendedPropertyMapper = extendedPropertyMapper; - _dataColumnMapper = dataColumnMapper; - } - - public override async Task MapToSnapshot(ModelDataRepository dataRepository) - { - var snapshot = await SnapshotFrom(dataRepository, x => { x.Name = SnapshotValueFor(dataRepository.Name); }); - - snapshot.ExtendedProperties = await _extendedPropertyMapper.MapToSnapshots(dataRepository.ExtendedProperties); - snapshot.Columns = await mapColumns(dataRepository.AllButBaseGrid().Where(column => !dataRepository.ColumnIsInRelatedColumns(column))); - snapshot.BaseGrid = await _dataColumnMapper.MapToSnapshot(dataRepository.BaseGrid); - return snapshot; - } - - private Task mapColumns(IEnumerable dataRepositoryColumns) - { - return _dataColumnMapper.MapToSnapshots(dataRepositoryColumns); - } - - public override async Task MapToModel(SnapshotDataRepository snapshot, SnapshotContext snapshotContext) - { - var dataRepository = new ModelDataRepository(); - var contextWithDataRepository = new SnapshotContextWithDataRepository(dataRepository, snapshotContext); - MapSnapshotPropertiesToModel(snapshot, dataRepository); - - dataRepository.Add(await _dataColumnMapper.MapToModel(snapshot.BaseGrid, contextWithDataRepository)); - dataRepository.AddColumns(await _dataColumnMapper.MapToModels(snapshot.Columns, contextWithDataRepository)); - - var extendedProperties = await _extendedPropertyMapper.MapToModels(snapshot.ExtendedProperties, snapshotContext); - extendedProperties?.Each(dataRepository.ExtendedProperties.Add); - - return dataRepository; - } + var snapshot = await SnapshotFrom(dataRepository, x => { x.Name = SnapshotValueFor(dataRepository.Name); }); + + snapshot.ExtendedProperties = await _extendedPropertyMapper.MapToSnapshots(dataRepository.ExtendedProperties); + snapshot.Columns = await mapColumns(dataRepository.AllButBaseGrid().Where(column => !dataRepository.ColumnIsInRelatedColumns(column))); + snapshot.BaseGrid = await _dataColumnMapper.MapToSnapshot(dataRepository.BaseGrid); + return snapshot; + } + + private Task mapColumns(IEnumerable dataRepositoryColumns) + { + return _dataColumnMapper.MapToSnapshots(dataRepositoryColumns); + } + + public override async Task MapToModel(SnapshotDataRepository snapshot, SnapshotContext snapshotContext) + { + var dataRepository = new ModelDataRepository(); + var contextWithDataRepository = new SnapshotContextWithDataRepository(dataRepository, snapshotContext); + MapSnapshotPropertiesToModel(snapshot, dataRepository); + + dataRepository.Add(await _dataColumnMapper.MapToModel(snapshot.BaseGrid, contextWithDataRepository)); + dataRepository.AddColumns(await _dataColumnMapper.MapToModels(snapshot.Columns, contextWithDataRepository)); + + var extendedProperties = await _extendedPropertyMapper.MapToModels(snapshot.ExtendedProperties, snapshotContext); + extendedProperties?.Each(dataRepository.ExtendedProperties.Add); + + return dataRepository; } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/DescriptorConditionMapper.cs b/src/PKSim.Core/Snapshots/Mappers/DescriptorConditionMapper.cs index 9796a17ca..5a983a952 100644 --- a/src/PKSim.Core/Snapshots/Mappers/DescriptorConditionMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/DescriptorConditionMapper.cs @@ -5,77 +5,75 @@ using PKSim.Assets; using SnapshotDescriptorCondition = PKSim.Core.Snapshots.DescriptorCondition; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class DescriptorConditionMapper : SnapshotMapperBase { - - public class DescriptorConditionMapper : SnapshotMapperBase + private readonly IOSPSuiteLogger _logger; + const string MATCH_TAG = "MatchTag"; + + public DescriptorConditionMapper(IOSPSuiteLogger logger) { - private readonly IOSPSuiteLogger _logger; - const string MATCH_TAG = "MatchTag"; + _logger = logger; + } - public DescriptorConditionMapper(IOSPSuiteLogger logger) - { - _logger = logger; - } + public override async Task MapToSnapshot(ITagCondition descriptorCondition) + { + var tagCondition = descriptorCondition as TagCondition; + var snapshot = await SnapshotFrom(descriptorCondition); + snapshot.Tag = tagCondition?.Tag; + snapshot.Type = typeFrom(descriptorCondition); + return snapshot; + } - public override async Task MapToSnapshot(ITagCondition descriptorCondition) - { - var tagCondition = descriptorCondition as TagCondition; - var snapshot = await SnapshotFrom(descriptorCondition); - snapshot.Tag = tagCondition?.Tag; - snapshot.Type = typeFrom(descriptorCondition); - return snapshot; - } + public override Task MapToModel(SnapshotDescriptorCondition snapshot, SnapshotContext snapshotContext) + { + return Task.FromResult(descriptorConditionFrom(snapshot)); + } - public override Task MapToModel(SnapshotDescriptorCondition snapshot, SnapshotContext snapshotContext) + private ITagCondition descriptorConditionFrom(SnapshotDescriptorCondition snapshot) + { + var tag = snapshot.Tag; + switch (snapshot.Type) { - return Task.FromResult(descriptorConditionFrom(snapshot)); + case Constants.IN_CONTAINER: + return new InContainerCondition(tag); + case Constants.ALL_TAG: + return new MatchAllCondition(); + case Constants.IN_PARENT: + return new InParentCondition(); + case MATCH_TAG: + return new MatchTagCondition(tag); + case Constants.NOT_IN_CONTAINER: + return new NotInContainerCondition(tag); + case Constants.NOT: + return new NotMatchTagCondition(tag); } - private ITagCondition descriptorConditionFrom(SnapshotDescriptorCondition snapshot) - { - var tag = snapshot.Tag; - switch (snapshot.Type) - { - case Constants.IN_CONTAINER: - return new InContainerCondition(tag); - case Constants.ALL_TAG: - return new MatchAllCondition(); - case Constants.IN_PARENT: - return new InParentCondition(); - case MATCH_TAG: - return new MatchTagCondition(tag); - case Constants.NOT_IN_CONTAINER: - return new NotInContainerCondition(tag); - case Constants.NOT: - return new NotMatchTagCondition(tag); - } - - //This should never happen - _logger.AddError(PKSimConstants.Error.CannotCreateDescriptorFromSnapshotFor(snapshot.Type)); - return null; - } + //This should never happen + _logger.AddError(PKSimConstants.Error.CannotCreateDescriptorFromSnapshotFor(snapshot.Type)); + return null; + } - private string typeFrom(ITagCondition tagCondition) + private string typeFrom(ITagCondition tagCondition) + { + switch (tagCondition) { - switch (tagCondition) - { - case InContainerCondition _: - return Constants.IN_CONTAINER; - case MatchAllCondition _: - return Constants.ALL_TAG; - case MatchTagCondition _: - return MATCH_TAG; - case InParentCondition _: - return Constants.IN_PARENT; - case NotInContainerCondition _: - return Constants.NOT_IN_CONTAINER; - case NotMatchTagCondition _: - return Constants.NOT; - } - - _logger.AddError(PKSimConstants.Error.CannotCreateDescriptorSnapshotFor(tagCondition.GetType().FullName)); - return null; + case InContainerCondition _: + return Constants.IN_CONTAINER; + case MatchAllCondition _: + return Constants.ALL_TAG; + case MatchTagCondition _: + return MATCH_TAG; + case InParentCondition _: + return Constants.IN_PARENT; + case NotInContainerCondition _: + return Constants.NOT_IN_CONTAINER; + case NotMatchTagCondition _: + return Constants.NOT; } + + _logger.AddError(PKSimConstants.Error.CannotCreateDescriptorSnapshotFor(tagCondition.GetType().FullName)); + return null; } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/DiseaseStateMapper.cs b/src/PKSim.Core/Snapshots/Mappers/DiseaseStateMapper.cs index ae545e0da..5563d3988 100644 --- a/src/PKSim.Core/Snapshots/Mappers/DiseaseStateMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/DiseaseStateMapper.cs @@ -2,6 +2,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.UnitSystem; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Assets; using PKSim.Core.Model; @@ -9,104 +10,103 @@ using SnapshotDiseaseState = PKSim.Core.Snapshots.DiseaseState; using ModelOriginData = PKSim.Core.Model.OriginData; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class DiseaseStateContext : SnapshotContext { - public class DiseaseStateContext : SnapshotContext + public ModelOriginData OriginData { get; } + + public DiseaseStateContext(ModelOriginData originData, SnapshotContext baseContext) : base(baseContext) { - public ModelOriginData OriginData { get; } + OriginData = originData; + } +} - public DiseaseStateContext(ModelOriginData originData, SnapshotContext baseContext) : base(baseContext) - { - OriginData = originData; - } +public class DiseaseStateMapper : SnapshotMapperBase +{ + private readonly IDiseaseStateRepository _diseaseStateRepository; + private readonly ParameterMapper _parameterMapper; + private readonly IDimensionRepository _dimensionRepository; + + public DiseaseStateMapper( + IDiseaseStateRepository diseaseStateRepository, + ParameterMapper parameterMapper, + IDimensionRepository dimensionRepository + ) + { + _diseaseStateRepository = diseaseStateRepository; + _parameterMapper = parameterMapper; + _dimensionRepository = dimensionRepository; } - public class DiseaseStateMapper : SnapshotMapperBase + public override Task MapToSnapshot(ModelOriginData originData) { - private readonly IDiseaseStateRepository _diseaseStateRepository; - private readonly ParameterMapper _parameterMapper; - private readonly IDimensionRepository _dimensionRepository; - - public DiseaseStateMapper( - IDiseaseStateRepository diseaseStateRepository, - ParameterMapper parameterMapper, - IDimensionRepository dimensionRepository - ) - { - _diseaseStateRepository = diseaseStateRepository; - _parameterMapper = parameterMapper; - _dimensionRepository = dimensionRepository; - } + var diseaseState = originData?.DiseaseState; + if (diseaseState == null || diseaseState.IsHealthy) + return Task.FromResult(null); - public override Task MapToSnapshot(ModelOriginData originData) + var snapshot = new SnapshotDiseaseState { - var diseaseState = originData?.DiseaseState; - if (diseaseState == null || diseaseState.IsHealthy) - return Task.FromResult(null); - - var snapshot = new SnapshotDiseaseState - { - Name = diseaseState.Name, - }; + Name = diseaseState.Name, + }; - if (originData.DiseaseStateParameters.Any()) - snapshot.Parameters = originData.DiseaseStateParameters.Select(namedParameterFrom).ToArray(); + if (originData.DiseaseStateParameters.Any()) + snapshot.Parameters = originData.DiseaseStateParameters.Select(namedParameterFrom).ToArray(); - return Task.FromResult(snapshot); - } + return Task.FromResult(snapshot); + } - public override Task MapToModel(SnapshotDiseaseState diseaseStateSnapshot, DiseaseStateContext diseaseStateContext) - { - var originData = diseaseStateContext.OriginData; + public override Task MapToModel(SnapshotDiseaseState diseaseStateSnapshot, DiseaseStateContext diseaseStateContext) + { + var originData = diseaseStateContext.OriginData; - if (diseaseStateSnapshot == null) - return Task.FromResult(originData); + if (diseaseStateSnapshot == null) + return Task.FromResult(originData); - var diseaseState = _diseaseStateRepository.AllFor(originData.Population).FindByName(diseaseStateSnapshot.Name); - if (diseaseState == null) - throw new PKSimException(PKSimConstants.Error.CannotFindDiseaseState(diseaseStateSnapshot.Name, originData.Population.DisplayName)); + var diseaseState = _diseaseStateRepository.AllFor(originData.Population).FindByName(diseaseStateSnapshot.Name); + if (diseaseState == null) + throw new PKSimException(PKSimConstants.Error.CannotFindDiseaseState(diseaseStateSnapshot.Name, originData.Population.DisplayName)); - originData.DiseaseState = diseaseState; - diseaseState.Parameters.Each(x => + originData.DiseaseState = diseaseState; + diseaseState.Parameters.Each(x => + { + var diseaseStateParameter = new OriginDataParameter { Name = x.Name, Value = x.Value, Unit = x.DisplayUnitName() }; + var snapshotParameter = diseaseStateSnapshot.Parameters.FindByName(x.Name); + if (snapshotParameter != null) { - var diseaseStateParameter = new OriginDataParameter { Name = x.Name, Value = x.Value, Unit = x.DisplayUnitName() }; - var snapshotParameter = diseaseStateSnapshot.Parameters.FindByName(x.Name); - if (snapshotParameter != null) - { - diseaseStateParameter.Value = baseParameterValueFrom(snapshotParameter, x.Value); - diseaseStateParameter.Unit = snapshotParameter.Unit; - } + diseaseStateParameter.Value = baseParameterValueFrom(snapshotParameter, x.Value); + diseaseStateParameter.Unit = snapshotParameter.Unit; + } - originData.AddDiseaseStateParameter(diseaseStateParameter); - }); + originData.AddDiseaseStateParameter(diseaseStateParameter); + }); - return Task.FromResult(originData); - } + return Task.FromResult(originData); + } - private Parameter namedParameterFrom(OriginDataParameter parameter) - { - return parameterFrom(parameter, _dimensionRepository.DimensionForUnit(parameter.Unit)).WithName(parameter.Name); - } + private Parameter namedParameterFrom(OriginDataParameter parameter) + { + return parameterFrom(parameter, _dimensionRepository.DimensionForUnit(parameter.Unit)).WithName(parameter.Name); + } - private Parameter parameterFrom(OriginDataParameter parameter, IDimension dimension) - { - if (parameter == null) - return null; + private Parameter parameterFrom(OriginDataParameter parameter, IDimension dimension) + { + if (parameter == null) + return null; - return _parameterMapper.ParameterFrom(parameter.Value, parameter.Unit, dimension); - } + return _parameterMapper.ParameterFrom(parameter.Value, parameter.Unit, dimension); + } - private double baseParameterValueFrom(Parameter snapshot, double defaultValueInBaseUnit) => - baseParameterValueFrom(snapshot, _dimensionRepository.DimensionForUnit(snapshot.Unit), defaultValueInBaseUnit); + private double baseParameterValueFrom(Parameter snapshot, double defaultValueInBaseUnit) => + baseParameterValueFrom(snapshot, _dimensionRepository.DimensionForUnit(snapshot.Unit), defaultValueInBaseUnit); - private double baseParameterValueFrom(Parameter snapshot, IDimension dimension, double defaultValueInBaseUnit) - { - if (snapshot?.Value == null) - return defaultValueInBaseUnit; + private double baseParameterValueFrom(Parameter snapshot, IDimension dimension, double defaultValueInBaseUnit) + { + if (snapshot?.Value == null) + return defaultValueInBaseUnit; - var unit = dimension.Unit(ModelValueFor(snapshot.Unit)); - return dimension.UnitValueToBaseUnitValue(unit, snapshot.Value.Value); - } + var unit = dimension.Unit(ModelValueFor(snapshot.Unit)); + return dimension.UnitValueToBaseUnitValue(unit, snapshot.Value.Value); } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/EventMappingMapper.cs b/src/PKSim.Core/Snapshots/Mappers/EventMappingMapper.cs index 27ea5010b..4563d49c1 100644 --- a/src/PKSim.Core/Snapshots/Mappers/EventMappingMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/EventMappingMapper.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Model; namespace PKSim.Core.Snapshots.Mappers diff --git a/src/PKSim.Core/Snapshots/Mappers/ExplicitFormulaMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ExplicitFormulaMapper.cs index 8e5ea9e02..8629e77f9 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ExplicitFormulaMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ExplicitFormulaMapper.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; using OSPSuite.Utility.Extensions; using PKSim.Core.Repositories; using SnapshotExplicitFormula = PKSim.Core.Snapshots.ExplicitFormula; diff --git a/src/PKSim.Core/Snapshots/Mappers/ExpressionContainerMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ExpressionContainerMapper.cs index 95655e3e3..902d6635c 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ExpressionContainerMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ExpressionContainerMapper.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Collections; using OSPSuite.Utility.Extensions; using PKSim.Assets; diff --git a/src/PKSim.Core/Snapshots/Mappers/ExpressionProfileMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ExpressionProfileMapper.cs index 04d13fa4b..3eaeb5dea 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ExpressionProfileMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ExpressionProfileMapper.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; using PKSim.Core.Commands; using PKSim.Core.Model; using PKSim.Core.Services; diff --git a/src/PKSim.Core/Snapshots/Mappers/FormulaUsablePathMapper.cs b/src/PKSim.Core/Snapshots/Mappers/FormulaUsablePathMapper.cs index 944e8c17d..677c9199c 100644 --- a/src/PKSim.Core/Snapshots/Mappers/FormulaUsablePathMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/FormulaUsablePathMapper.cs @@ -1,6 +1,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Extensions; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Repositories; using SnapshotFormulaUsablePath = PKSim.Core.Snapshots.FormulaUsablePath; diff --git a/src/PKSim.Core/Snapshots/Mappers/GroupingDefinitionMapper.cs b/src/PKSim.Core/Snapshots/Mappers/GroupingDefinitionMapper.cs index b7564d6a6..e02d20577 100644 --- a/src/PKSim.Core/Snapshots/Mappers/GroupingDefinitionMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/GroupingDefinitionMapper.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Core.Model.PopulationAnalyses; using PKSim.Core.Repositories; diff --git a/src/PKSim.Core/Snapshots/Mappers/IndividualMapper.cs b/src/PKSim.Core/Snapshots/Mappers/IndividualMapper.cs index fe3b86733..145d93c23 100644 --- a/src/PKSim.Core/Snapshots/Mappers/IndividualMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/IndividualMapper.cs @@ -1,6 +1,7 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; using OSPSuite.Utility.Extensions; using PKSim.Core.Model; using PKSim.Core.Services; diff --git a/src/PKSim.Core/Snapshots/Mappers/ObjectBaseSnapshotMapperBase.cs b/src/PKSim.Core/Snapshots/Mappers/ObjectBaseSnapshotMapperBase.cs index 36167fbb9..aee6eeff1 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ObjectBaseSnapshotMapperBase.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ObjectBaseSnapshotMapperBase.cs @@ -1,54 +1,10 @@ -using System; -using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Snapshots.Mappers; -namespace PKSim.Core.Snapshots.Mappers -{ - public abstract class ObjectBaseSnapshotMapperBase : SnapshotMapperBase - where TModel : IWithName, IWithDescription - where TSnapshot : IWithName, IWithDescription, new() - where TSnapshotContext : SnapshotContext - { - protected void MapModelPropertiesToSnapshot(TModel model, TSnapshot snapshot) - { - snapshot.Name = SnapshotValueFor(model.Name); - snapshot.Description = SnapshotValueFor(model.Description); - } - - protected virtual void MapSnapshotPropertiesToModel(TSnapshot snapshot, TModel model) - { - model.Name = snapshot.Name; - model.Description = snapshot.Description; - } - - protected override Task SnapshotFrom(TModel model, Action configurationAction = null) - { - return base.SnapshotFrom(model, snapshot => - { - MapModelPropertiesToSnapshot(model, snapshot); - configurationAction?.Invoke(snapshot); - }); - } - } - - public abstract class ObjectBaseSnapshotMapperBase : ObjectBaseSnapshotMapperBase - where TModel : IWithName, IWithDescription - where TSnapshot : IWithName, IWithDescription, new() - where TSnapshotContext : SnapshotContext - { - public abstract Task MapToSnapshot(TModel model, TModelContext context); - - public sealed override Task MapToSnapshot(TModel model) - { - return Task.FromException(new ModelMapToSnapshotNotSupportedException()); - } - } - - public abstract class ObjectBaseSnapshotMapperBase : ObjectBaseSnapshotMapperBase - where TModel : IWithName, IWithDescription - where TSnapshot : IWithName, IWithDescription, new() - { - - } +namespace PKSim.Core.Snapshots.Mappers; +public abstract class ObjectBaseSnapshotMapperBase : ObjectBaseSnapshotMapperBase + where TModel : IWithName, IWithDescription + where TSnapshot : IWithName, IWithDescription, new() +{ } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/ObservedDataCollectionMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ObservedDataCollectionMapper.cs index 73a952c5f..60d5c0d64 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ObservedDataCollectionMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ObservedDataCollectionMapper.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using ModelObservedDataCollection = PKSim.Core.Model.PopulationAnalyses.ObservedDataCollection; using ModelObservedDataCurveOptions = PKSim.Core.Model.PopulationAnalyses.ObservedDataCurveOptions; diff --git a/src/PKSim.Core/Snapshots/Mappers/ObserverMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ObserverMapper.cs index 0367fcc51..0ef232a95 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ObserverMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ObserverMapper.cs @@ -2,6 +2,7 @@ using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Builder; using OSPSuite.Core.Domain.Descriptors; +using OSPSuite.Core.Extensions; using OSPSuite.Core.Services; using OSPSuite.Utility.Extensions; using PKSim.Assets; @@ -26,8 +27,8 @@ public class ObserverMapper : ObjectBaseSnapshotMapperBase MapToSnapshot(ModelObserver observe case AmountObserverBuilder _: snapshot.Type = AMOUNT_OBSERVER; break; - case ContainerObserverBuilder _:; + case ContainerObserverBuilder _: + ; snapshot.Type = CONTAINER_OBSERVER; break; } @@ -81,11 +83,9 @@ public override async Task MapToModel(SnapshotObserver snapshot, var moleculeList = await _moleculeListMapper.MapToModel(snapshot.MoleculeList, snapshotContext); observer.MoleculeList.Update(moleculeList); return observer; - } - - private ObserverBuilder createObserverFrom(SnapshotObserver snapshot) + private ModelObserver createObserverFrom(SnapshotObserver snapshot) { if (string.IsNullOrEmpty(snapshot.Type)) return null; diff --git a/src/PKSim.Core/Snapshots/Mappers/ObserverSetMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ObserverSetMapper.cs index 274122cbd..cb101c88f 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ObserverSetMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ObserverSetMapper.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using OSPSuite.Core.Extensions; using OSPSuite.Utility.Extensions; using PKSim.Core.Model; using SnapshotObserverSet = PKSim.Core.Snapshots.ObserverSet; diff --git a/src/PKSim.Core/Snapshots/Mappers/ObserverSetMappingMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ObserverSetMappingMapper.cs index d2fcb8cac..1fbc59be7 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ObserverSetMappingMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ObserverSetMappingMapper.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Assets; using PKSim.Core.Model; diff --git a/src/PKSim.Core/Snapshots/Mappers/OntogenyMapper.cs b/src/PKSim.Core/Snapshots/Mappers/OntogenyMapper.cs index 1c40976b5..f70a935f7 100644 --- a/src/PKSim.Core/Snapshots/Mappers/OntogenyMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/OntogenyMapper.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Model; using PKSim.Core.Repositories; using SnapshotOntogeny = PKSim.Core.Snapshots.Ontogeny; diff --git a/src/PKSim.Core/Snapshots/Mappers/OriginDataMapper.cs b/src/PKSim.Core/Snapshots/Mappers/OriginDataMapper.cs index 6dacb7f2c..c627d9b4d 100644 --- a/src/PKSim.Core/Snapshots/Mappers/OriginDataMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/OriginDataMapper.cs @@ -4,6 +4,7 @@ using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Domain.UnitSystem; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Assets; using PKSim.Core.Model; diff --git a/src/PKSim.Core/Snapshots/Mappers/OutputMappingMapper.cs b/src/PKSim.Core/Snapshots/Mappers/OutputMappingMapper.cs index a48bdfb0d..e192a107a 100644 --- a/src/PKSim.Core/Snapshots/Mappers/OutputMappingMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/OutputMappingMapper.cs @@ -1,10 +1,10 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; -using OSPSuite.Core.Domain.ParameterIdentifications; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Extensions; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Assets; using ModelOutputMapping = OSPSuite.Core.Domain.OutputMapping; using SnapshotOutputMapping = PKSim.Core.Snapshots.OutputMapping; diff --git a/src/PKSim.Core/Snapshots/Mappers/OutputSchemaMapper.cs b/src/PKSim.Core/Snapshots/Mappers/OutputSchemaMapper.cs index 0e1f23e0c..a68b093c0 100644 --- a/src/PKSim.Core/Snapshots/Mappers/OutputSchemaMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/OutputSchemaMapper.cs @@ -4,6 +4,7 @@ using PKSim.Core.Model; using SnapshotOutputSchema = PKSim.Core.Snapshots.OutputSchema; using ModelOutputSchema = OSPSuite.Core.Domain.OutputSchema; +using OSPSuite.Core.Extensions; namespace PKSim.Core.Snapshots.Mappers { diff --git a/src/PKSim.Core/Snapshots/Mappers/OutputSelectionsMapper.cs b/src/PKSim.Core/Snapshots/Mappers/OutputSelectionsMapper.cs index d11f74d04..6a0f24a16 100644 --- a/src/PKSim.Core/Snapshots/Mappers/OutputSelectionsMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/OutputSelectionsMapper.cs @@ -2,6 +2,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Assets; using PKSim.Core.Services; diff --git a/src/PKSim.Core/Snapshots/Mappers/ParameterContainerSnapshotMapperBase.cs b/src/PKSim.Core/Snapshots/Mappers/ParameterContainerSnapshotMapperBase.cs index 4a1b4a001..bfe76d33e 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ParameterContainerSnapshotMapperBase.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ParameterContainerSnapshotMapperBase.cs @@ -2,7 +2,10 @@ using System.Collections.Generic; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; +using OSPSuite.Core.Snapshots; using PKSim.Core.Model; +using OSPSuite.Core.Snapshots.Mappers; namespace PKSim.Core.Snapshots.Mappers { diff --git a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationAlgorithmMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationAlgorithmMapper.cs index ed3982cd9..da4fb810b 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationAlgorithmMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationAlgorithmMapper.cs @@ -1,5 +1,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain.ParameterIdentifications; +using OSPSuite.Core.Extensions; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; namespace PKSim.Core.Snapshots.Mappers diff --git a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationAnalysisMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationAnalysisMapper.cs index b221c4256..ac8822c7b 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationAnalysisMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationAnalysisMapper.cs @@ -3,6 +3,8 @@ using OSPSuite.Core.Chart.ParameterIdentifications; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Services; +using OSPSuite.Core.Extensions; +using OSPSuite.Core.Snapshots.Mappers; namespace PKSim.Core.Snapshots.Mappers { diff --git a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationConfigurationMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationConfigurationMapper.cs index 3d42a7966..ee591488a 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationConfigurationMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationConfigurationMapper.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain.ParameterIdentifications; +using OSPSuite.Core.Snapshots.Mappers; using ModelParameterIdentificationConfiguration = OSPSuite.Core.Domain.ParameterIdentifications.ParameterIdentificationConfiguration; using SnapshotParameterIdentificationConfiguration = PKSim.Core.Snapshots.ParameterIdentificationConfiguration; diff --git a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationMapper.cs index c9c47227b..63c5cf01b 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationMapper.cs @@ -1,6 +1,7 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; using OSPSuite.Core.Services; using OSPSuite.Utility.Extensions; using PKSim.Assets; diff --git a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationRunModeMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationRunModeMapper.cs index 8cfff6ebe..ab915000f 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationRunModeMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ParameterIdentificationRunModeMapper.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using OSPSuite.Core.Domain.ParameterIdentifications; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using ModelParameterIdentificationRunMode = OSPSuite.Core.Domain.ParameterIdentifications.ParameterIdentificationRunMode; using SnapshotParameterIdentificationRunMode = PKSim.Core.Snapshots.ParameterIdentificationRunMode; diff --git a/src/PKSim.Core/Snapshots/Mappers/ParameterMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ParameterMapper.cs index 92cd1b6e2..1c2098048 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ParameterMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ParameterMapper.cs @@ -8,8 +8,10 @@ using OSPSuite.Core.Domain.UnitSystem; using OSPSuite.Core.Extensions; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Assets; +using static OSPSuite.Core.Extensions.SnapshotMapperBaseExtensions; using static PKSim.Core.CoreConstants.ContainerName; using SnapshotParameter = PKSim.Core.Snapshots.Parameter; using SnapshotTableFormula = PKSim.Core.Snapshots.TableFormula; @@ -137,11 +139,11 @@ public virtual Task LocalizedParameterFrom(IParameter parame return createFrom(parameter, x => { x.Path = pathResolverFunc(parameter); }); } - public virtual Task LocalizedParametersFrom(IEnumerable parameters) => orderByPath(SnapshotMapperBaseExtensions.MapTo(parameters, LocalizedParameterFrom)); + public virtual Task LocalizedParametersFrom(IEnumerable parameters) => orderByPath(MapTo(parameters, LocalizedParameterFrom)); public virtual Task LocalizedParametersFrom(IEnumerable parameters, Func pathResolverFunc) { - return orderByPath(SnapshotMapperBaseExtensions.MapTo(parameters, x => LocalizedParameterFrom(x, pathResolverFunc))); + return orderByPath(MapTo(parameters, x => LocalizedParameterFrom(x, pathResolverFunc))); } private async Task orderByPath(Task localizedParametersTask) diff --git a/src/PKSim.Core/Snapshots/Mappers/ParameterRangeMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ParameterRangeMapper.cs index 0883b113e..78b25e739 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ParameterRangeMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ParameterRangeMapper.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using OSPSuite.Core.Snapshots.Mappers; using SnapshotParameterRange = PKSim.Core.Snapshots.ParameterRange; using ModelParameterRange = PKSim.Core.Model.ParameterRange; diff --git a/src/PKSim.Core/Snapshots/Mappers/PopulationAnalysisChartMapper.cs b/src/PKSim.Core/Snapshots/Mappers/PopulationAnalysisChartMapper.cs index 1d8a9943b..ed1d264ca 100644 --- a/src/PKSim.Core/Snapshots/Mappers/PopulationAnalysisChartMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/PopulationAnalysisChartMapper.cs @@ -1,5 +1,6 @@ using System.Linq; using System.Threading.Tasks; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Core.Model.PopulationAnalyses; using ModelPopulationAnalysisChart = PKSim.Core.Model.PopulationAnalyses.PopulationAnalysisChart; diff --git a/src/PKSim.Core/Snapshots/Mappers/PopulationAnalysisMapper.cs b/src/PKSim.Core/Snapshots/Mappers/PopulationAnalysisMapper.cs index 99061fab3..89314192e 100644 --- a/src/PKSim.Core/Snapshots/Mappers/PopulationAnalysisMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/PopulationAnalysisMapper.cs @@ -3,6 +3,8 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Core.Model.PopulationAnalyses; using ModelPopulationAnalysis = PKSim.Core.Model.PopulationAnalyses.PopulationAnalysis; diff --git a/src/PKSim.Core/Snapshots/Mappers/PopulationMapper.cs b/src/PKSim.Core/Snapshots/Mappers/PopulationMapper.cs index 4e7fe8e30..476f1c785 100644 --- a/src/PKSim.Core/Snapshots/Mappers/PopulationMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/PopulationMapper.cs @@ -6,6 +6,7 @@ using PKSim.Core.Model; using SnapshotPopulation = PKSim.Core.Snapshots.Population; using ModelPopulation = PKSim.Core.Model.Population; +using OSPSuite.Core.Extensions; namespace PKSim.Core.Snapshots.Mappers { diff --git a/src/PKSim.Core/Snapshots/Mappers/ProcessMappingMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ProcessMappingMapper.cs index b74c0a28b..1456b8a02 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ProcessMappingMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ProcessMappingMapper.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Model; namespace PKSim.Core.Snapshots.Mappers diff --git a/src/PKSim.Core/Snapshots/Mappers/ProjectMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ProjectMapper.cs index 2f9f10115..0921b26ed 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ProjectMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ProjectMapper.cs @@ -3,7 +3,9 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Extensions; using PKSim.Assets; using PKSim.Core.Model; @@ -157,7 +159,7 @@ private Task allParameterIdentificationsFrom(Par SnapshotContext snapshotContext) => _parameterIdentificationMapper.MapToModels(snapshotParameterIdentifications, snapshotContext); - private Task allQualificationPlansFrom(QualificationPlan[] qualificationPlans, SnapshotContext snapshotContext) + private Task allQualificationPlansFrom(QualificationPlan[] qualificationPlans, SnapshotContext snapshotContext) => _qualificationPlanMapper.MapToModels(qualificationPlans, snapshotContext); private async Task mapSimulationComparisonsToSnapshots(IReadOnlyCollection allSimulationComparisons) @@ -175,7 +177,7 @@ private async Task mapSimulationsToSnapshots(IReadOnlyCollection mapQualificationPlansToSnapshots(IReadOnlyCollection allQualificationPlans) + private async Task mapQualificationPlansToSnapshots(IReadOnlyCollection allQualificationPlans) { return await _qualificationPlanMapper.MapToSnapshots(allQualificationPlans); } @@ -224,7 +226,7 @@ private Task updateProjectClassifications(SnapshotProject snapshot, SnapshotCont snapshot.SimulationComparisonClassifications, snapshotContext, project.AllSimulationComparisons), _classificationSnapshotTask.UpdateProjectClassifications( snapshot.ParameterIdentificationClassifications, snapshotContext, project.AllParameterIdentifications), - _classificationSnapshotTask.UpdateProjectClassifications( + _classificationSnapshotTask.UpdateProjectClassifications( snapshot.QualificationPlanClassifications, snapshotContext, project.AllQualificationPlans), }; @@ -252,9 +254,9 @@ private void addParameterIdentificationToProject(ModelProject project, ModelPara project.AddParameterIdentification, project.AllParameterIdentifications); } - private void addQualificationPlanToProject(ModelProject project, Model.QualificationPlan qualificationPlan) + private void addQualificationPlanToProject(ModelProject project, OSPSuite.Core.Domain.QualificationPlan qualificationPlan) { - addClassifiableToProject(project, qualificationPlan, project.AddQualificationPlan, project.AllQualificationPlans); + addClassifiableToProject(project, qualificationPlan, project.AddQualificationPlan, project.AllQualificationPlans); } private void logDuplicateEntryError(T subject) where T : class, IWithId, IWithName diff --git a/src/PKSim.Core/Snapshots/Mappers/ProtocolMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ProtocolMapper.cs index ccdd52d02..ab166c7c6 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ProtocolMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ProtocolMapper.cs @@ -5,6 +5,7 @@ using PKSim.Core.Repositories; using ModelProtocol = PKSim.Core.Model.Protocol; using SnapshotProtocol = PKSim.Core.Snapshots.Protocol; +using OSPSuite.Core.Extensions; namespace PKSim.Core.Snapshots.Mappers { diff --git a/src/PKSim.Core/Snapshots/Mappers/QualificationPlanMapper.cs b/src/PKSim.Core/Snapshots/Mappers/QualificationPlanMapper.cs index 2aa26605a..309281afa 100644 --- a/src/PKSim.Core/Snapshots/Mappers/QualificationPlanMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/QualificationPlanMapper.cs @@ -1,9 +1,9 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; using OSPSuite.Utility.Extensions; -using PKSim.Core.Model; using SnapshotQualificationPlan = PKSim.Core.Snapshots.QualificationPlan; -using ModelQualificationPlan = PKSim.Core.Model.QualificationPlan; +using ModelQualificationPlan = OSPSuite.Core.Domain.QualificationPlan; namespace PKSim.Core.Snapshots.Mappers { diff --git a/src/PKSim.Core/Snapshots/Mappers/QualificationStepMapper.cs b/src/PKSim.Core/Snapshots/Mappers/QualificationStepMapper.cs index 052c66a8c..9a036f6e7 100644 --- a/src/PKSim.Core/Snapshots/Mappers/QualificationStepMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/QualificationStepMapper.cs @@ -2,6 +2,8 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Assets; using PKSim.Core.Model; using SnapshotQualificationStep = PKSim.Core.Snapshots.QualificationStep; @@ -36,7 +38,7 @@ private void mapQualificationStepPropertiesToSnapsot(SnapshotQualificationStep s snapshot.Subject = runSimulationQualificationStep.Simulation.Name; break; default: - throw new ArgumentException(PKSimConstants.Error.CouldNotFindQualificationStep(snapshot.Type)); + throw new ArgumentException(OSPSuite.Assets.Error.CouldNotFindQualificationStep(snapshot.Type)); } } @@ -47,7 +49,7 @@ public override Task MapToModel(SnapshotQualificationStep sn var qualificationStep = createQualificationStepFrom(snapshot.Type); if (qualificationStep == null) { - _logger.AddWarning(PKSimConstants.Error.CouldNotFindQualificationStep(snapshot.Type)); + _logger.AddWarning(OSPSuite.Assets.Error.CouldNotFindQualificationStep(snapshot.Type)); return Task.FromResult(null); } @@ -75,7 +77,7 @@ private void mapQualificationStepPropertiesToModel(IQualificationStep qualificat runSimulationQualificationStep.Simulation = simulation; break; default: - throw new ArgumentException(PKSimConstants.Error.NotMappingDefinedForQualificationStep(qualificationStep.GetType().Name)); + throw new ArgumentException(OSPSuite.Assets.Error.NotMappingDefinedForQualificationStep(qualificationStep.GetType().Name)); } } diff --git a/src/PKSim.Core/Snapshots/Mappers/QuantityInfoMapper.cs b/src/PKSim.Core/Snapshots/Mappers/QuantityInfoMapper.cs index 01e7a34fd..61f56b241 100644 --- a/src/PKSim.Core/Snapshots/Mappers/QuantityInfoMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/QuantityInfoMapper.cs @@ -1,6 +1,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Extensions; +using OSPSuite.Core.Snapshots.Mappers; using ModelQuantityInfo = OSPSuite.Core.Domain.Data.QuantityInfo; using SnapshotQuantityInfo = PKSim.Core.Snapshots.QuantityInfo; diff --git a/src/PKSim.Core/Snapshots/Mappers/RandomPopulationSettingsMapper.cs b/src/PKSim.Core/Snapshots/Mappers/RandomPopulationSettingsMapper.cs index 902cb6a74..fa93bd9ba 100644 --- a/src/PKSim.Core/Snapshots/Mappers/RandomPopulationSettingsMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/RandomPopulationSettingsMapper.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Assets; using PKSim.Core.Mappers; using PKSim.Core.Model; diff --git a/src/PKSim.Core/Snapshots/Mappers/SchemaMapper.cs b/src/PKSim.Core/Snapshots/Mappers/SchemaMapper.cs index 26f227dae..5f6ca56ed 100644 --- a/src/PKSim.Core/Snapshots/Mappers/SchemaMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/SchemaMapper.cs @@ -5,6 +5,7 @@ using PKSim.Core.Model; using ModelSchema = PKSim.Core.Model.Schema; using SnapshotSchema = PKSim.Core.Snapshots.Schema; +using OSPSuite.Core.Extensions; namespace PKSim.Core.Snapshots.Mappers { diff --git a/src/PKSim.Core/Snapshots/Mappers/SimulationComparisonMapper.cs b/src/PKSim.Core/Snapshots/Mappers/SimulationComparisonMapper.cs index 28642edbb..f5e77084e 100644 --- a/src/PKSim.Core/Snapshots/Mappers/SimulationComparisonMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/SimulationComparisonMapper.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; using OSPSuite.Utility.Extensions; using PKSim.Core.Chart; using PKSim.Core.Model; diff --git a/src/PKSim.Core/Snapshots/Mappers/SimulationMapper.cs b/src/PKSim.Core/Snapshots/Mappers/SimulationMapper.cs index 9338189c4..957076f8d 100644 --- a/src/PKSim.Core/Snapshots/Mappers/SimulationMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/SimulationMapper.cs @@ -2,9 +2,13 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using OSPSuite.Assets; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Services; +using OSPSuite.Core.Extensions; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Exceptions; using OSPSuite.Utility.Extensions; using PKSim.Assets; @@ -273,7 +277,7 @@ private string usedSimulationSubject(ModelSimulation simulation, PKSimProject public override async Task MapToModel(SnapshotSimulation snapshot, SimulationContext snapshotContext) { var project = snapshotContext.Project; - _logger.AddInfo(PKSimConstants.Information.LoadingSimulation(snapshot.Name, snapshotContext.NumberOfSimulationsLoaded, snapshotContext.NumberOfSimulationsToLoad), project.Name); + _logger.AddInfo(Captions.LoadingSimulation(snapshot.Name, snapshotContext.NumberOfSimulationsLoaded, snapshotContext.NumberOfSimulationsToLoad), project.Name); //Local cache of ids' that will be used to retrieve original building block parameters as the project is only registered //in global context once the whole snapshot mapping process is completed @@ -353,7 +357,7 @@ private Model.CompoundProcess findProcess(PKSimProject project, CompoundProcessS //This might be a process that was deselected explicitly by the user var molecule = simulationSubject.MoleculeByName(snapshotInteraction.MoleculeName); - return molecule == null ? null : new NoInteractionProcess {MoleculeName = molecule.Name}; + return molecule == null ? null : new NoInteractionProcess { MoleculeName = molecule.Name }; } private async Task runSimulation(SnapshotSimulation snapshot, ModelSimulation simulation) @@ -381,7 +385,7 @@ private Task analysesFrom(ModelSimula return Task.FromResult(new List().ToArray()); var project = simulationContext.Project; - var curveChartContext = new SimulationAnalysisContext(project.AllObservedData, simulationContext) {RunSimulation = simulationContext.Run}; + var curveChartContext = new SimulationAnalysisContext(project.AllObservedData, simulationContext) { RunSimulation = simulationContext.Run }; var individualSimulation = simulation as IndividualSimulation; if (individualSimulation?.DataRepository != null) diff --git a/src/PKSim.Core/Snapshots/Mappers/SnapshotMapper.cs b/src/PKSim.Core/Snapshots/Mappers/SnapshotMapper.cs index 9c990a78f..0fe4a66de 100644 --- a/src/PKSim.Core/Snapshots/Mappers/SnapshotMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/SnapshotMapper.cs @@ -1,135 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using OSPSuite.Utility.Collections; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Model; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +public class SnapshotContext : SnapshotContext { - public class SnapshotContext + //This constructor should only be called when initiation the project load and the project is not available + public SnapshotContext() : base(new PKSimProject(), ProjectVersions.Current) { - public int Version { get; } - public PKSimProject Project { get; } - - //This constructor should only be called when initiation the project load and the project is not available - public SnapshotContext() : this(new PKSimProject(), ProjectVersions.Current) - { - } - - public SnapshotContext(PKSimProject project, int version) - { - Project = project; - Version = version; - } - - public SnapshotContext(SnapshotContext baseContext) : this(baseContext.Project, baseContext.Version) - { - } - - /// - /// Returns true if the format is V9 or earlier - /// - public bool IsV9FormatOrEarlier => Version <= ProjectVersions.V9; - - /// - /// Returns true if the format is V10 or earlier - /// - public bool IsV10FormatOrEarlier => Version <= ProjectVersions.V10; - - - /// - /// Returns true if the format is V11 or earlier - /// - public bool IsV11FormatOrEarlier => Version <= ProjectVersions.V11; } - public interface ISnapshotMapper + public SnapshotContext(PKSimProject project, int version) : base(project, version) { - /// - /// Given a object, returns the corresponding snapshot. - /// - /// - /// is thrown if a snapshot could not be found for the given - /// - /// - Task MapToSnapshot(object model); - - /// - /// Given a object, returns the corresponding model. - /// - /// Snapshot object convert to model - /// Snapshot context - /// - /// is thrown if a snapshot could not be found for the given - /// - /// - Task MapToModel(object snapshot, SnapshotContext snapshotContext); - - /// - /// Returns the snapshot type for the model type - /// - /// Model type for which the snapshot type should be found - /// - /// is thrown if a snapshot could not be found for the given - /// model type - /// - Type SnapshotTypeFor(); - - /// - /// Returns the mapper associated with a given - /// Is thrown if no mapper could be found for the given type - /// - ISnapshotMapper MapperFor(object modelOrSnapshotType); - - /// - /// Returns the mapper associated with a given - /// Is thrown if no mapper could be found for the given type - /// - ISnapshotMapper MapperFor(Type modelOrSnapshotType); } - public interface ISnapshotMapperWithContext: ISnapshotMapper where TSnapshotContext : SnapshotContext + public SnapshotContext(SnapshotContext baseContext) : base(baseContext.Project, baseContext.Version) { - /// - /// Given a object, returns the corresponding model using the - /// as context - /// - /// - /// is thrown if a snapshot could not be found for the given - /// - /// - Task MapToModel(TSnapshot snapshot, TSnapshotContext snapshotContext); } - public class SnapshotMapper : ISnapshotMapper - { - private readonly List _allMappers; - - public SnapshotMapper(IRepository snapshotMapperRepository) - { - _allMappers = snapshotMapperRepository.All().ToList(); - } + /// + /// Returns true if the format is V9 or earlier + /// + public bool IsV9FormatOrEarlier => Version <= ProjectVersions.V9; - public Task MapToSnapshot(object model) => MapperFor(model).MapToSnapshot(model); + /// + /// Returns true if the format is V10 or earlier + /// + public bool IsV10FormatOrEarlier => Version <= ProjectVersions.V10; - public Task MapToModel(object snapshot, SnapshotContext snapshotContext) => MapperFor(snapshot).MapToModel(snapshot, snapshotContext); - public Type SnapshotTypeFor() - { - var modelType = typeof(T); - return MapperFor(modelType).SnapshotTypeFor(); - } - - public ISnapshotMapper MapperFor(object modelOrSnapshotObject) => MapperFor(modelOrSnapshotObject.GetType()); - - public ISnapshotMapper MapperFor(Type modelOrSnapshotType) - { - var mapper = _allMappers.FirstOrDefault(x => x.IsSatisfiedBy(modelOrSnapshotType)); - if (mapper != null) - return mapper; - - throw new SnapshotNotFoundException(modelOrSnapshotType); - } - } + /// + /// Returns true if the format is V11 or earlier + /// + public bool IsV11FormatOrEarlier => Version <= ProjectVersions.V11; } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/SnapshotMapperBase.cs b/src/PKSim.Core/Snapshots/Mappers/SnapshotMapperBase.cs index 5d61f54e6..096fc969e 100644 --- a/src/PKSim.Core/Snapshots/Mappers/SnapshotMapperBase.cs +++ b/src/PKSim.Core/Snapshots/Mappers/SnapshotMapperBase.cs @@ -1,93 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using OSPSuite.Utility; -using OSPSuite.Utility.Extensions; +using OSPSuite.Core.Snapshots.Mappers; namespace PKSim.Core.Snapshots.Mappers { - public interface ISnapshotMapperSpecification : ISnapshotMapper, ISpecification - { - } - - public abstract class SnapshotMapperBase : ISnapshotMapperSpecification, ISnapshotMapperWithContext - where TSnapshot : new() - where TSnapshotContext : SnapshotContext - { - public virtual async Task MapToSnapshot(object model) => await MapToSnapshot(model.DowncastTo()); - - public async Task MapToModel(object snapshot, SnapshotContext snapshotContext) => await MapToModel(snapshot.DowncastTo(), snapshotContext.DowncastTo()); - - public abstract Task MapToModel(TSnapshot snapshot, TSnapshotContext context); - - public abstract Task MapToSnapshot(TModel model); - - public Type SnapshotTypeFor() => typeof(TSnapshot); - - public ISnapshotMapper MapperFor(object modelOrSnapshotType) => this; - - public ISnapshotMapper MapperFor(Type modelOrSnapshotType) => this; - - public virtual bool IsSatisfiedBy(Type item) - { - return item.IsAnImplementationOf() || item.IsAnImplementationOf(); - } - - protected string SnapshotValueFor(string value) => !string.IsNullOrEmpty(value) ? value : null; - - protected T? SnapshotValueFor(T value, T defaultValue = default(T)) where T : struct - { - if (Equals(value, defaultValue)) - return null; - - return value; - } - - protected T? SnapshotValueFor(T? value, T defaultValue = default(T)) where T : struct - { - if (value == null) - return null; - - return SnapshotValueFor(value.Value, defaultValue); - } - - protected T[] SnapshotValueFor(IEnumerable values) - { - if (values == null) - return null; - - var array = values.ToArray(); - return !array.Any() ? null : array; - } - - protected string ModelValueFor(string snapshotValue) => snapshotValue ?? ""; - - protected T ModelValueFor(T? snapshotValue, T defaultValue = default(T)) where T : struct - { - return snapshotValue.GetValueOrDefault(defaultValue); - } - - protected virtual Task SnapshotFrom(TModel model, Action configurationAction = null) - { - var snapshot = new TSnapshot(); - configurationAction?.Invoke(snapshot); - return Task.FromResult(snapshot); - } - } - - public abstract class SnapshotMapperBase : SnapshotMapperBase - where TSnapshot : new() where TSnapshotContext : SnapshotContext - { - public abstract Task MapToSnapshot(TModel model, TModelContext context); - - public sealed override Task MapToSnapshot(TModel model) - { - return Task.FromException(new ModelMapToSnapshotNotSupportedException()); - } - } - public abstract class SnapshotMapperBase : SnapshotMapperBase where TSnapshot : new() { } + } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/SnapshotMapperBaseExtensions.cs b/src/PKSim.Core/Snapshots/Mappers/SnapshotMapperBaseExtensions.cs index c5a257e30..f16b070f3 100644 --- a/src/PKSim.Core/Snapshots/Mappers/SnapshotMapperBaseExtensions.cs +++ b/src/PKSim.Core/Snapshots/Mappers/SnapshotMapperBaseExtensions.cs @@ -1,109 +1,35 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Collections.Generic; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Extensions; +using static OSPSuite.Core.Extensions.SnapshotMapperBaseExtensions; -namespace PKSim.Core.Snapshots.Mappers +namespace PKSim.Core.Snapshots.Mappers; + +/// +/// Extensions instead of method in base class to simplify testing +/// +public static class SnapshotMapperBaseExtensions { /// - /// Extensions instead of method in base class to simplify testing + /// Maps a list of snapshot to the corresponding model arrays. If the list if null or empty, null will be returned /// - public static class SnapshotMapperBaseExtensions + public static Task MapToModels(this ParameterContainerSnapshotMapperBase mapper, IEnumerable snapshots, TSnapshotContext context) + where TSnapshot : ParameterContainerSnapshotBase, new() + where TModel : IContainer + where TSnapshotContext : SnapshotContext { - /// - /// Maps a list of snapshot to the corresponding model arrays. If the list if null or empty, null will be returned - /// - public static Task MapToModels(this SnapshotMapperBase mapper, IEnumerable snapshots, TSnapshotContext snapshotContext) - where TSnapshot : new() - where TSnapshotContext : SnapshotContext - { - return MapToModels(mapper, snapshots, s => mapper.MapToModel(s, snapshotContext)); - } - - /// - /// Maps a list of snapshot to the corresponding model arrays. If the list if null or empty, null will be returned - /// - public static Task MapToModels(this SnapshotMapperBase mapper, IEnumerable snapshots, Func> mapToModelFunc) - where TSnapshot : new() - where TSnapshotContext : SnapshotContext - { - return MapTo(snapshots, mapToModelFunc); - } - - /// - /// Maps a list of snapshot to the corresponding model arrays. If the list if null or empty, null will be returned - /// - public static Task MapToModels(this ObjectBaseSnapshotMapperBase mapper, IEnumerable snapshots, TSnapshotContext context) - where TSnapshot : IWithName, IWithDescription, new() - where TModel : IWithName, IWithDescription - where TSnapshotContext : SnapshotContext - { - return MapToModels(mapper, snapshots, s => mapper.MapToModel(s, context)); - } - - /// - /// Maps a list of snapshot to the corresponding model arrays. If the list if null or empty, null will be returned - /// - public static Task MapToModels(this ParameterContainerSnapshotMapperBase mapper, IEnumerable snapshots, TSnapshotContext context) - where TSnapshot : ParameterContainerSnapshotBase, new() - where TModel : IContainer - where TSnapshotContext : SnapshotContext - { - return MapToModels(mapper, snapshots, s => mapper.MapToModel(s, context)); - } - - /// - /// Maps a list of models to the corresponding snapshot arrays. If the list if null or empty, null will be returned - /// - public static Task MapToSnapshots(this SnapshotMapperBase mapper, IEnumerable models) where TSnapshot : new() - where TSnapshotContext : SnapshotContext - { - return MapTo(models, mapper.MapToSnapshot); - } - - /// - /// Maps a list of models to the corresponding snapshot arrays. If the list if null or empty, null will be returned - /// - public static Task MapToSnapshots(this SnapshotMapperBase mapper, IEnumerable models, TModelContext modelContext) - where TSnapshot : new() - where TSnapshotContext : SnapshotContext - { - return MapTo(models, m => mapper.MapToSnapshot(m, modelContext)); - } - - /// - /// Maps a list of models to the corresponding snapshot arrays. If the list if null or empty, null will be returned - /// - public static Task MapToSnapshots(this ObjectBaseSnapshotMapperBase mapper, IEnumerable models, TModelContext modelContext) - where TSnapshot : IWithName, IWithDescription, new() - where TModel : IWithName, IWithDescription - where TSnapshotContext : SnapshotContext - { - return MapTo(models, m => mapper.MapToSnapshot(m, modelContext)); - } - - /// - /// Maps a list of models to the corresponding snapshot arrays. If the list if null or empty, null will be returned - /// - public static Task MapToSnapshots(this ParameterContainerSnapshotMapperBase mapper, IEnumerable models, TModelContext modelContext) - where TSnapshot : ParameterContainerSnapshotBase, new() - where TModel : IContainer - where TSnapshotContext : SnapshotContext - { - return MapTo(models, m => mapper.MapToSnapshot(m, modelContext)); - } - - public static async Task MapTo(IEnumerable sources, Func> mapToFunc) - { - var list = sources?.ToList(); - - if (list == null || !list.Any()) - return null; - - var targets = (await Task.WhenAll(list.Select(mapToFunc))).Where(x => x != null).ToArray(); + return mapper.MapToModels(snapshots, s => mapper.MapToModel(s, context)); + } - return !targets.Any() ? null : targets; - } + /// + /// Maps a list of models to the corresponding snapshot arrays. If the list if null or empty, null will be returned + /// + public static Task MapToSnapshots(this ParameterContainerSnapshotMapperBase mapper, IEnumerable models, TModelContext modelContext) + where TSnapshot : ParameterContainerSnapshotBase, new() + where TModel : IContainer + where TSnapshotContext : SnapshotContext + { + return MapTo(models, m => mapper.MapToSnapshot(m, modelContext)); } } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/Mappers/SolverSettingsMapper.cs b/src/PKSim.Core/Snapshots/Mappers/SolverSettingsMapper.cs index 73ae4f311..00ff9c412 100644 --- a/src/PKSim.Core/Snapshots/Mappers/SolverSettingsMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/SolverSettingsMapper.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Model; using SnapshotSolverSettings = PKSim.Core.Snapshots.SolverSettings; using ModelSolverSettings = OSPSuite.Core.Domain.SolverSettings; diff --git a/src/PKSim.Core/Snapshots/Mappers/ValueOriginMapper.cs b/src/PKSim.Core/Snapshots/Mappers/ValueOriginMapper.cs index 4dacb7393..815f269a8 100644 --- a/src/PKSim.Core/Snapshots/Mappers/ValueOriginMapper.cs +++ b/src/PKSim.Core/Snapshots/Mappers/ValueOriginMapper.cs @@ -1,5 +1,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Snapshots; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Repositories; using ModelValueOrigin = OSPSuite.Core.Domain.ValueOrigin; using SnapshotValueOrigin = PKSim.Core.Snapshots.ValueOrigin; diff --git a/src/PKSim.Core/Snapshots/Services/SnapshotTask.cs b/src/PKSim.Core/Snapshots/Services/SnapshotTask.cs index be7e309ef..e1cb7fb66 100644 --- a/src/PKSim.Core/Snapshots/Services/SnapshotTask.cs +++ b/src/PKSim.Core/Snapshots/Services/SnapshotTask.cs @@ -1,231 +1,64 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Services; -using OSPSuite.Utility; -using PKSim.Assets; +using OSPSuite.Core.Snapshots.Mappers; +using OSPSuite.Core.Snapshots.Services; using PKSim.Core.Model; using PKSim.Core.Services; using PKSim.Core.Snapshots.Mappers; +using SnapshotContext = PKSim.Core.Snapshots.Mappers.SnapshotContext; -namespace PKSim.Core.Snapshots.Services -{ - public interface ISnapshotTask - { - /// - /// Exports the given to snapshot. User will be ask to specify the file where the - /// snapshot will be exported - /// - Task ExportModelToSnapshotAsync(T modelToExport) where T : class, IObjectBase; - - /// - /// Exports the given to snapshot file - /// - Task ExportModelToSnapshotAsync(T modelToExport, string fileFullPath) where T : class, IObjectBase; - - /// - /// Exports the given to file. is already a - /// snapshot object and won't be mapped to snapshot - /// - Task ExportSnapshotAsync(IWithName snapshotObject); - - Task> LoadModelsFromSnapshotFileAsync() where T : class, IObjectBase; - - Task> LoadSnapshotsAsync(string fileName); +namespace PKSim.Core.Snapshots.Services; - Task> LoadModelsFromSnapshotFileAsync(string fileName) where T : class; - - Task LoadProjectFromSnapshotFileAsync(string fileName, bool runSimulations = true); - - Task LoadProjectFromSnapshotAsync(Project snapshot, bool runSimulations); - - Task LoadSnapshotFromFileAsync(string fileName) where T : IWithName; +public interface ISnapshotTask : ISnapshotTask +{ + /// + /// Returns true if was created with a version of PK-Sim fully supporting + /// snapshot (7.3 and higher) otherwise false + /// + bool IsVersionCompatibleWithSnapshotExport(T objectToExport) where T : class, IWithCreationMetaData; - /// - /// Returns true if was created with a version of PK-Sim fully supporting - /// snapshot (7.3 and higher) otherwise false - /// - bool IsVersionCompatibleWithSnapshotExport(T objectToExport) where T : class, IWithCreationMetaData; + Task LoadModelFromProjectFileAsync(string fileName, PKSimBuildingBlockType buildingBlockType, string buildingBlockName); +} - Task LoadModelFromProjectFileAsync(string fileName, PKSimBuildingBlockType buildingBlockType, string buildingBlockName); +public class SnapshotTask : SnapshotTask, ISnapshotTask +{ + private readonly IPKSimProjectRetriever _projectRetriever; + private readonly ProjectMapper _projectMapper; + + public SnapshotTask( + IDialogCreator dialogCreator, + IJsonSerializer jsonSerializer, + ISnapshotMapper snapshotMapper, + IExecutionContext executionContext, + IObjectTypeResolver objectTypeResolver, + IPKSimProjectRetriever projectRetriever, + ProjectMapper projectMapper) : base(jsonSerializer, snapshotMapper, dialogCreator, objectTypeResolver, executionContext) + { + _projectRetriever = projectRetriever; + _projectMapper = projectMapper; } - public class SnapshotTask : ISnapshotTask + public bool IsVersionCompatibleWithSnapshotExport(T objectToExport) where T : class, IWithCreationMetaData { - private readonly IDialogCreator _dialogCreator; - private readonly IExecutionContext _executionContext; - private readonly IObjectTypeResolver _objectTypeResolver; - private readonly IPKSimProjectRetriever _projectRetriever; - private readonly ProjectMapper _projectMapper; - private readonly IJsonSerializer _jsonSerializer; - private readonly ISnapshotMapper _snapshotMapper; - - public SnapshotTask( - IDialogCreator dialogCreator, - IJsonSerializer jsonSerializer, - ISnapshotMapper snapshotMapper, - IExecutionContext executionContext, - IObjectTypeResolver objectTypeResolver, - IPKSimProjectRetriever projectRetriever, - ProjectMapper projectMapper) - { - _dialogCreator = dialogCreator; - _executionContext = executionContext; - _objectTypeResolver = objectTypeResolver; - _projectRetriever = projectRetriever; - _projectMapper = projectMapper; - _jsonSerializer = jsonSerializer; - _snapshotMapper = snapshotMapper; - } - - public async Task ExportModelToSnapshotAsync(T modelToExport) where T : class, IObjectBase - { - if (modelToExport == null) - return; - - var fileName = fileNameForExport(modelToExport); - if (string.IsNullOrEmpty(fileName)) - return; - - await ExportModelToSnapshotAsync(modelToExport, fileName); - } - - public Task ExportModelToSnapshotAsync(T modelToExport, string fileFullPath) where T : class, IObjectBase - { - _executionContext.Load(modelToExport); - return exportSnapshotFor(modelToExport, fileFullPath); - } - - private string fileNameForExport(IWithName objectToExport) - { - var message = PKSimConstants.UI.SelectSnapshotExportFile(objectToExport.Name, _objectTypeResolver.TypeFor(objectToExport)); - return _dialogCreator.AskForFileToSave(message, Constants.Filter.JSON_FILE_FILTER, Constants.DirectoryKey.REPORT, objectToExport.Name); - } - - public async Task ExportSnapshotAsync(IWithName snapshotObject) - { - var fileName = fileNameForExport(snapshotObject); - if (string.IsNullOrEmpty(fileName)) - return; - - await saveSnapshotToFile(snapshotObject, fileName); - } - - public Task> LoadModelsFromSnapshotFileAsync() where T : class, IObjectBase - { - var fileName = fileNameForSnapshotImport(); - return LoadModelsFromSnapshotFileAsync(fileName); - } + var projectCreationVersion = objectToExport?.Creation.InternalVersion; + if (projectCreationVersion == null) + return false; - private string fileNameForSnapshotImport() - { - var message = PKSimConstants.UI.LoadObjectFromSnapshot(_objectTypeResolver.TypeFor()); - return _dialogCreator.AskForFileToOpen(message, Constants.Filter.JSON_FILE_FILTER, Constants.DirectoryKey.REPORT); - } - - public async Task LoadSnapshotFromFileAsync(string fileName) where T : IWithName - { - var snapshots = await LoadSnapshotsAsync(fileName); - var snapshot = snapshots.FirstOrDefault(); - - if (snapshot != null && string.IsNullOrEmpty(snapshot.Name)) - snapshot.Name = FileHelper.FileNameFromFileFullPath(fileName); - - return snapshot; - } - - public async Task> LoadSnapshotsAsync(string fileName) - { - var snapshots = await loadSnapshot(fileName, typeof(T)); - return snapshots.OfType(); - } - - private async Task> loadSnapshot(string fileName, Type snapshotType) - { - if (string.IsNullOrEmpty(fileName)) - return Enumerable.Empty(); - - return await _jsonSerializer.DeserializeAsArray(fileName, snapshotType); - } - - public async Task> LoadModelsFromSnapshotFileAsync(string fileName) where T : class - { - var snapshotType = _snapshotMapper.SnapshotTypeFor(); - var snapshots = await loadSnapshot(fileName, snapshotType); - - return await loadModelsFromSnapshotsAsync(snapshots); - } - - private async Task> loadModelsFromSnapshotsAsync(IEnumerable snapshots) - { - if (snapshots == null) - return Enumerable.Empty(); - - //This method is typically called when loading a building block snapshot directly (e.g exported as dev). - //In this case, we are not supporting any project conversion and we just create one with the current version - var snapshotContext = new SnapshotContext(_projectRetriever.Current, ProjectVersions.Current); - var tasks = snapshots.Select(x => _snapshotMapper.MapToModel(x, snapshotContext)); - var models = await Task.WhenAll(tasks); - return models.OfType(); - } - - private async Task loadModelFromSnapshot(object snapshot) - { - if (snapshot == null) - return default(T); - - var models = await loadModelsFromSnapshotsAsync(new[] {snapshot}); - return models.FirstOrDefault(); - } - - public async Task LoadProjectFromSnapshotFileAsync(string fileName, bool runSimulations = true) - { - var projectSnapshot = await LoadSnapshotFromFileAsync(fileName); - var project = await LoadProjectFromSnapshotAsync(projectSnapshot, runSimulations); - return projectWithUpdatedProperties(project, FileHelper.FileNameFromFileFullPath(fileName)); - } - - public async Task LoadProjectFromSnapshotAsync(Project snapshot, bool runSimulations) - { - var project = await _projectMapper.MapToModel(snapshot, new ProjectContext(runSimulations)); - return projectWithUpdatedProperties(project, snapshot?.Name); - } - - private PKSimProject projectWithUpdatedProperties(PKSimProject project, string name) - { - if (project == null) - return null; - - project.HasChanged = true; - project.Name = name; - return project; - } - - public bool IsVersionCompatibleWithSnapshotExport(T objectToExport) where T : class, IWithCreationMetaData - { - var projectCreationVersion = objectToExport?.Creation.InternalVersion; - if (projectCreationVersion == null) - return false; + return projectCreationVersion >= ProjectVersions.V7_3_0; + } - return projectCreationVersion >= ProjectVersions.V7_3_0; - } + public async Task LoadModelFromProjectFileAsync(string fileName, PKSimBuildingBlockType buildingBlockType, string buildingBlockName) + { + var projectSnapshot = await LoadSnapshotFromFileAsync(fileName); + var snapshot = projectSnapshot.BuildingBlockByTypeAndName(buildingBlockType, buildingBlockName); + return await LoadModelFromSnapshot(snapshot); + } - public async Task LoadModelFromProjectFileAsync(string fileName, PKSimBuildingBlockType buildingBlockType, string buildingBlockName) - { - var projectSnapshot = await LoadSnapshotFromFileAsync(fileName); - var snapshot = projectSnapshot.BuildingBlockByTypeAndName(buildingBlockType, buildingBlockName); - return await loadModelFromSnapshot(snapshot); - } + protected override Task ProjectFrom(Project snapshot, bool runSimulations) => _projectMapper.MapToModel(snapshot, new ProjectContext(runSimulations)); - private async Task exportSnapshotFor(T objectToExport, string fileName) - { - var snapshot = await _snapshotMapper.MapToSnapshot(objectToExport); - await saveSnapshotToFile(snapshot, fileName); - } + protected override OSPSuite.Core.Snapshots.Mappers.SnapshotContext GetSnapshotContext() => new SnapshotContext(_projectRetriever.Current, ProjectVersions.Current); - private Task saveSnapshotToFile(object snapshot, string fileName) => _jsonSerializer.Serialize(snapshot, fileName); - } + protected override PKSimProject GetProject() => _projectRetriever.Current; } \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/SnapshotNotFoundException.cs b/src/PKSim.Core/Snapshots/SnapshotNotFoundException.cs deleted file mode 100644 index 6cf25e9f4..000000000 --- a/src/PKSim.Core/Snapshots/SnapshotNotFoundException.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using PKSim.Assets; - -namespace PKSim.Core.Snapshots -{ - public class SnapshotNotFoundException : Exception - { - public SnapshotNotFoundException(Type modelType) : base(PKSimConstants.Error.SnapshotNotFoundFor(modelType.FullName)) - { - } - } - - - public class SnapshotMapToModelNotSupportedException : NotSupportedException - { - public SnapshotMapToModelNotSupportedException() : base(PKSimConstants.Error.MapToModelNotSupportedWithoutContext(typeof(TModel).Name, typeof(TContext).Name)) - { - } - } - - public class ModelMapToSnapshotNotSupportedException : NotSupportedException - { - public ModelMapToSnapshotNotSupportedException() : base(PKSimConstants.Error.MapToSnapshotNotSupportedWithoutContext(typeof(TSnapshot).Name, typeof(TContext).Name)) - { - } - } -} \ No newline at end of file diff --git a/src/PKSim.Core/Snapshots/SnapshotOutdatedException.cs b/src/PKSim.Core/Snapshots/SnapshotOutdatedException.cs deleted file mode 100644 index b932f5884..000000000 --- a/src/PKSim.Core/Snapshots/SnapshotOutdatedException.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Collections.Generic; -using OSPSuite.Utility.Exceptions; -using OSPSuite.Utility.Extensions; -using PKSim.Assets; - -namespace PKSim.Core.Snapshots -{ - public class SnapshotOutdatedException : OSPSuiteException - { - public SnapshotOutdatedException(string reason) : base($"{PKSimConstants.Error.SnapshotIsOutdated}\n\n{reason}") - { - } - } - - public class SnapshotFileMismatchException : OSPSuiteException - { - public SnapshotFileMismatchException(string desiredType, IEnumerable reasons) : base($"{PKSimConstants.Error.SnapshotFileMismatch(desiredType)}\n\n{reasons.ToString("\n")}") - { - } - } -} \ No newline at end of file diff --git a/src/PKSim.Infrastructure/ORM/Repositories/RemoteTemplateRepository.cs b/src/PKSim.Infrastructure/ORM/Repositories/RemoteTemplateRepository.cs index 91e5f0920..1a41c71be 100644 --- a/src/PKSim.Infrastructure/ORM/Repositories/RemoteTemplateRepository.cs +++ b/src/PKSim.Infrastructure/ORM/Repositories/RemoteTemplateRepository.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using OSPSuite.Core.Domain; using OSPSuite.Core.Extensions; +using OSPSuite.Core.Services; using OSPSuite.Utility; using OSPSuite.Utility.Collections; using OSPSuite.Utility.Exceptions; @@ -14,7 +15,6 @@ using PKSim.Core; using PKSim.Core.Model; using PKSim.Core.Repositories; -using PKSim.Core.Services; using PKSim.Core.Snapshots.Services; namespace PKSim.Infrastructure.ORM.Repositories @@ -116,7 +116,7 @@ private IReadOnlyList metabolitesFor(RemoteTemplate remoteTempla protected override void DoStart() { var snapshots = Task.Run(() => _jsonSerializer.Deserialize(_configuration.RemoteTemplateSummaryPath)).Result; - + snapshots.Templates.Each(x => { var (version, repositoryUrl) = extractDataFromUrl(x.Url); @@ -140,15 +140,15 @@ protected override void DoStart() var segments = new Uri(url).Segments; //The url does not respect the expected format. Returned the default raw url - if(segments.Length != 5) + if (segments.Length != 5) return invalidUrl; var versionSegment = segments[3]; - if(!versionSegment.StartsWith("v") || !versionSegment.EndsWith("/")) + if (!versionSegment.StartsWith("v") || !versionSegment.EndsWith("/")) return invalidUrl; //Removes the v at the beginning end the "/" at the ned - var version = versionSegment.Substring(1, versionSegment.Length -2); + var version = versionSegment.Substring(1, versionSegment.Length - 2); return (version, $"https://github.com/{segments[1]}{segments[2]}tree/{versionSegment}"); } diff --git a/src/PKSim.Infrastructure/PKSim.Infrastructure.csproj b/src/PKSim.Infrastructure/PKSim.Infrastructure.csproj index a7b0910fe..8e1c5d051 100644 --- a/src/PKSim.Infrastructure/PKSim.Infrastructure.csproj +++ b/src/PKSim.Infrastructure/PKSim.Infrastructure.csproj @@ -35,15 +35,15 @@ - - - - - - - - - + + + + + + + + + diff --git a/src/PKSim.Infrastructure/Serialization/Json/ColorConverter.cs b/src/PKSim.Infrastructure/Serialization/Json/ColorConverter.cs deleted file mode 100644 index 1d4025194..000000000 --- a/src/PKSim.Infrastructure/Serialization/Json/ColorConverter.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Drawing; -using Newtonsoft.Json; -using OSPSuite.Core.Extensions; - -namespace PKSim.Infrastructure.Serialization.Json -{ - class ColorConverter : JsonConverter - { - public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) - { - if (value == null) - return; - - var c = (Color) value; - var hexString = $"{c.R:X2}{c.G:X2}{c.B:X2}"; - // Only add hex transparency if required as it does not seem to be widely supported by color readers. - var preFix = c.A == 255 ? "#" : $"#{c.A:X2}"; - hexString = $"{preFix}{hexString}"; - writer.WriteValue(hexString); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) - { - //this will never be called as default color reader will take precedence - return existingValue; - } - - public override bool CanRead => false; - - public override bool CanConvert(Type objectType) - { - return objectType.IsOneOf(typeof(Color), typeof(Color?)); - } - } -} \ No newline at end of file diff --git a/src/PKSim.Infrastructure/Serialization/Json/JsonSerializer.cs b/src/PKSim.Infrastructure/Serialization/Json/JsonSerializer.cs index b796644db..9f8e8e1b4 100644 --- a/src/PKSim.Infrastructure/Serialization/Json/JsonSerializer.cs +++ b/src/PKSim.Infrastructure/Serialization/Json/JsonSerializer.cs @@ -1,126 +1,29 @@ using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; -using Newtonsoft.Json.Schema.Generation; using OSPSuite.Utility.Extensions; -using PKSim.Core.Services; using PKSim.Core.Snapshots; namespace PKSim.Infrastructure.Serialization.Json { - public class JsonSerializer : IJsonSerializer + public class JsonSerializer : OSPSuite.Infrastructure.Serialization.Json.JsonSerializer { - private readonly JsonSerializerSettings _settings = new PKSimJsonSerializerSettings(); - - //Defines a static field as the free license only allows for a limited number of schema generation per hour - private static readonly ConcurrentDictionary _schemas = new ConcurrentDictionary(); - - public async Task Serialize(object objectToSerialize, string fileName) - { - var data = Serialize(objectToSerialize); - - using (var sw = new StreamWriter(fileName)) - { - await sw.WriteAsync(data); - } - } - - public string Serialize(object objectToSerialize) - { - return JsonConvert.SerializeObject(objectToSerialize, Formatting.Indented, _settings); - } - - public async Task DeserializeAsArray(string fileName, Type objectType) - { - string json; - using (var reader = new StreamReader(fileName)) - { - json = await reader.ReadToEndAsync(); - } - - return deserializeAsArrayFromString(json, objectType); - } - - public Task DeserializeAsArrayFromString(string jsonString, Type objectType) => - Task.FromResult(deserializeAsArrayFromString(jsonString, objectType)); - - public async Task DeserializeAsArrayFromString(string jsonString) - { - return (await DeserializeAsArrayFromString(jsonString, typeof(T))).OfType().ToArray(); - } - - private object[] deserializeAsArrayFromString(string json, Type objectType) + public JsonSerializer() { - var schema = validateSnapshot(objectType); - var deserializedSnapshot = JsonConvert.DeserializeObject(json, _settings); - - switch (deserializedSnapshot) - { - case JObject jsonObject: - return new[] { validatedObject(jsonObject, schema, objectType) }; - - case JArray array: - return array.Select(x => validatedObject(x, schema, objectType)).ToArray(); - default: - return null; - } + } - public async Task Deserialize(string fileName, Type objectType) - { - var deserializedObjects = await DeserializeAsArray(fileName, objectType); - return deserializedObjects.FirstOrDefault(); - } - - public async Task Deserialize(string fileName) where T : class - { - var deserializedObject = await Deserialize(fileName, typeof(T)); - return deserializedObject as T; - } - - public async Task DeserializeFromString(string jsonString, Type objectType) - { - var deserializedObjects = await DeserializeAsArrayFromString(jsonString, objectType); - return deserializedObjects.FirstOrDefault(); - } - - public async Task DeserializeFromString(string jsonString) where T:class - { - var deserializedObject = await DeserializeFromString(jsonString, typeof(T)); - return deserializedObject as T; - } - - private object validatedObject(JToken jToken, JSchema schema, Type snapshotType) + + protected override object ValidatedObject(JToken jToken, JSchema schema, Type snapshotType) { if (!requiresSchemaValidation(snapshotType)) return jToken.ToObject(snapshotType); - if (jToken.IsValid(schema, out IList errorMessages)) - return jToken.ToObject(snapshotType); - - throw new SnapshotFileMismatchException(snapshotType.Name, errorMessages); + return base.ValidatedObject(jToken, schema, snapshotType); } private bool requiresSchemaValidation(Type snapshotType) { return snapshotType.IsAnImplementationOf(); } - - private JSchema validateSnapshot(Type snapshotType) - { - return _schemas.GetOrAdd(snapshotType, createSchemaForType); - } - - private JSchema createSchemaForType(Type snapshotType) - { - var generator = new JSchemaGenerator {DefaultRequired = Required.Default}; - generator.GenerationProviders.Add(new StringEnumGenerationProvider()); - return generator.Generate(snapshotType); - } } } \ No newline at end of file diff --git a/src/PKSim.Infrastructure/Serialization/Json/NullabeDoubleJsonConverter.cs b/src/PKSim.Infrastructure/Serialization/Json/NullabeDoubleJsonConverter.cs deleted file mode 100644 index 867bd6bdd..000000000 --- a/src/PKSim.Infrastructure/Serialization/Json/NullabeDoubleJsonConverter.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using Newtonsoft.Json; -using OSPSuite.Utility.Format; - -namespace PKSim.Infrastructure.Serialization.Json -{ - public class NullabeDoubleJsonConverter : JsonConverter - { - private const int DOUBLE_PRECISION = 10; - - private readonly NumericFormatter _doubleFormatter = new NumericFormatter(new NumericFormatterOptions - { - AllowsScientificNotation = true, - DecimalPlace = DOUBLE_PRECISION - }); - - public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) - { - var d = (double?) value; - if (!d.HasValue) - return; - - var formatted = _doubleFormatter.Format(d.Value); - - double.TryParse(formatted, out double roundedFromString); - - writer.WriteValue(roundedFromString); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) - { - //this will never be called for nullable as double reader will take precedence - return 0; - } - - public override bool CanRead => false; - - public override bool CanConvert(Type objectType) - { - return objectType == typeof(double?); - } - } -} \ No newline at end of file diff --git a/src/PKSim.Infrastructure/Serialization/Json/PKSimJsonSerializerSettings.cs b/src/PKSim.Infrastructure/Serialization/Json/PKSimJsonSerializerSettings.cs deleted file mode 100644 index 82248e267..000000000 --- a/src/PKSim.Infrastructure/Serialization/Json/PKSimJsonSerializerSettings.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; - -namespace PKSim.Infrastructure.Serialization.Json -{ - public class PKSimJsonSerializerSettings : JsonSerializerSettings - { - public PKSimJsonSerializerSettings() - { - TypeNameHandling = TypeNameHandling.Auto; - NullValueHandling = NullValueHandling.Ignore; - ContractResolver = new WritablePropertiesOnlyResolver(); - Converters.Add(new StringEnumConverter()); - Converters.Add(new NullabeDoubleJsonConverter()); - Converters.Add(new ColorConverter()); - } - } -} \ No newline at end of file diff --git a/src/PKSim.Infrastructure/Serialization/Json/WritablePropertiesOnlyResolver.cs b/src/PKSim.Infrastructure/Serialization/Json/WritablePropertiesOnlyResolver.cs deleted file mode 100644 index 7e7ca51a2..000000000 --- a/src/PKSim.Infrastructure/Serialization/Json/WritablePropertiesOnlyResolver.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace PKSim.Infrastructure.Serialization.Json -{ - public class WritablePropertiesOnlyResolver : DefaultContractResolver - { - protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) - { - var props = base.CreateProperties(type, memberSerialization); - return props.Where(p => p.Writable).ToList(); - } - } - } \ No newline at end of file diff --git a/src/PKSim.Infrastructure/Serialization/Xml/Serializers/ClassifiableXmlSerializer.cs b/src/PKSim.Infrastructure/Serialization/Xml/Serializers/ClassifiableXmlSerializer.cs index 4becf4d1b..0df82f67f 100644 --- a/src/PKSim.Infrastructure/Serialization/Xml/Serializers/ClassifiableXmlSerializer.cs +++ b/src/PKSim.Infrastructure/Serialization/Xml/Serializers/ClassifiableXmlSerializer.cs @@ -1,4 +1,5 @@ -using PKSim.Core.Model; +using OSPSuite.Core.Domain; +using PKSim.Core.Model; using OSPSuite.Core.Serialization.Xml; namespace PKSim.Infrastructure.Serialization.Xml.Serializers diff --git a/src/PKSim.Infrastructure/Services/ObservedDataTask.cs b/src/PKSim.Infrastructure/Services/ObservedDataTask.cs index 812049a2e..a11d08197 100644 --- a/src/PKSim.Infrastructure/Services/ObservedDataTask.cs +++ b/src/PKSim.Infrastructure/Services/ObservedDataTask.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; -using System.Drawing; using System.Linq; using System.Threading.Tasks; -using OSPSuite.Assets; using OSPSuite.Core.Commands; using OSPSuite.Core.Commands.Core; using OSPSuite.Core.Domain; @@ -13,13 +11,13 @@ using OSPSuite.Core.Serialization.Xml; using OSPSuite.Core.Services; using OSPSuite.Presentation.Core; +using OSPSuite.Presentation.Presenters; using OSPSuite.Utility.Extensions; using PKSim.Assets; using PKSim.Core; using PKSim.Core.Model; using PKSim.Core.Services; using PKSim.Presentation.Presenters; -using PKSim.Presentation.Presenters.Snapshots; using IObservedDataTask = PKSim.Core.Services.IObservedDataTask; namespace PKSim.Infrastructure.Services @@ -48,7 +46,7 @@ public ObservedDataTask( IOutputMappingMatchingTask outputMappingMatchingTask, IConfirmationManager confirmationManager) : base(dialogCreator, executionContext, dataRepositoryTask, containerTask, - objectTypeResolver, confirmationManager) + objectTypeResolver, confirmationManager) { _projectRetriever = projectRetriever; _executionContext = executionContext; diff --git a/src/PKSim.Infrastructure/Services/VersionChecker.cs b/src/PKSim.Infrastructure/Services/VersionChecker.cs index 642d783d6..eaf450b91 100644 --- a/src/PKSim.Infrastructure/Services/VersionChecker.cs +++ b/src/PKSim.Infrastructure/Services/VersionChecker.cs @@ -3,6 +3,7 @@ using System.Net; using System.Threading.Tasks; using OSPSuite.Core.Domain; +using OSPSuite.Core.Services; using PKSim.Core.Services; namespace PKSim.Infrastructure.Services diff --git a/src/PKSim.Presentation/DTO/Snapshots/LoadFromSnapshotDTO.cs b/src/PKSim.Presentation/DTO/Snapshots/LoadFromSnapshotDTO.cs deleted file mode 100644 index 1a5302d3f..000000000 --- a/src/PKSim.Presentation/DTO/Snapshots/LoadFromSnapshotDTO.cs +++ /dev/null @@ -1,36 +0,0 @@ -using NPOI.HSSF.Util; -using OSPSuite.Core.Domain; -using OSPSuite.Presentation.DTO; -using OSPSuite.Utility.Validation; - -namespace PKSim.Presentation.DTO.Snapshots -{ - public class LoadFromSnapshotDTO : ValidatableDTO - { - private string _snapshotFile; - //By default, always run simulations - private bool _runSimulations = true; - - public virtual string SnapshotFile - { - get => _snapshotFile; - set => SetProperty(ref _snapshotFile, value); - } - - public virtual bool RunSimulations - { - get => _runSimulations; - set => SetProperty(ref _runSimulations, value); - } - - public LoadFromSnapshotDTO() - { - Rules.Add(AllRules.FileExists); - } - - private static class AllRules - { - public static IBusinessRule FileExists { get; } = GenericRules.FileExists(x => x.SnapshotFile); - } - } -} \ No newline at end of file diff --git a/src/PKSim.Presentation/PKSim.Presentation.csproj b/src/PKSim.Presentation/PKSim.Presentation.csproj index ce7fac3f0..5044ab52c 100644 --- a/src/PKSim.Presentation/PKSim.Presentation.csproj +++ b/src/PKSim.Presentation/PKSim.Presentation.csproj @@ -25,11 +25,11 @@ - + - - + + diff --git a/src/PKSim.Presentation/Presenters/Snapshots/LoadFromSnapshotPresenter.cs b/src/PKSim.Presentation/Presenters/Snapshots/LoadFromSnapshotPresenter.cs index 6725e454d..0076c26aa 100644 --- a/src/PKSim.Presentation/Presenters/Snapshots/LoadFromSnapshotPresenter.cs +++ b/src/PKSim.Presentation/Presenters/Snapshots/LoadFromSnapshotPresenter.cs @@ -1,55 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using OSPSuite.Assets; -using OSPSuite.Core; -using OSPSuite.Core.Domain; +using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Services; using OSPSuite.Presentation.Presenters; +using OSPSuite.Presentation.Views; using OSPSuite.Utility.Events; -using PKSim.Assets; +using PKSim.Core.Model; using PKSim.Core.Snapshots.Services; -using PKSim.Presentation.DTO.Snapshots; -using PKSim.Presentation.Views.Snapshots; +using Project = PKSim.Core.Snapshots.Project; namespace PKSim.Presentation.Presenters.Snapshots { - public interface ILoadFromSnapshotPresenter : IPresenter, IDisposablePresenter + public class LoadFromSnapshotPresenter : LoadFromSnapshotPresenter where T : class, IObjectBase { - /// - /// Starts the snapshot file selection process. Returns true if a file was selected of false if the - /// selection was canceled - /// - bool SelectFile(); - - Task StartAsync(); - - bool ModelIsDefined { get; } - - /// - /// File selected by the user containing the snapshot being loaded. - /// - string SnapshotFile { get; } - } - - public interface ILoadFromSnapshotPresenter : ILoadFromSnapshotPresenter where T : class, IObjectBase - { - IReadOnlyList LoadModelFromSnapshot(); - } - - public class LoadFromSnapshotPresenter : AbstractDisposablePresenter, ILoadFromSnapshotPresenter where T : class, IObjectBase - { - protected readonly ISnapshotTask _snapshotTask; - private readonly IDialogCreator _dialogCreator; - private readonly IObjectTypeResolver _objectTypeResolver; - private readonly IOSPSuiteLogger _logger; - private readonly IEventPublisher _eventPublisher; - private readonly ILogPresenter _logPresenter; - private readonly LoadFromSnapshotDTO _loadFromSnapshotDTO = new LoadFromSnapshotDTO(); - private IEnumerable _model; - public LoadFromSnapshotPresenter( ILoadFromSnapshotView view, ILogPresenter logPresenter, @@ -57,119 +19,8 @@ public LoadFromSnapshotPresenter( IDialogCreator dialogCreator, IObjectTypeResolver objectTypeResolver, IOSPSuiteLogger logger, - IEventPublisher eventPublisher) : base(view) - { - _snapshotTask = snapshotTask; - _dialogCreator = dialogCreator; - _objectTypeResolver = objectTypeResolver; - _logger = logger; - _logPresenter = logPresenter; - _eventPublisher = eventPublisher; - AddSubPresenters(_logPresenter); - _view.Caption = PKSimConstants.UI.LoadObjectFromSnapshot(typeToLoad); - _view.AddLogView(_logPresenter.BaseView); - _view.BindTo(_loadFromSnapshotDTO); - } - - public override bool ShouldClose - { - get - { - if (!ModelIsDefined) - return true; - - var shouldCancel = _dialogCreator.MessageBoxYesNo(Captions.ReallyCancel); - return shouldCancel == ViewResult.Yes; - } - } - - public IReadOnlyList LoadModelFromSnapshot() - { - if (!SelectFile()) - return null; - - _view.Display(); - ClearModel(_model); - return _view.Canceled ? null : _model.ToList(); - } - - public bool SelectFile() - { - var fileName = selectSnapshotFile(); - if (string.IsNullOrEmpty(fileName)) - return false; - - ClearModel(); - - _loadFromSnapshotDTO.SnapshotFile = fileName; - return true; - } - - private string selectSnapshotFile() - { - var message = PKSimConstants.UI.LoadObjectFromSnapshot(typeToLoad); - return _dialogCreator.AskForFileToOpen(message, Constants.Filter.JSON_FILE_FILTER, Constants.DirectoryKey.REPORT); - } - - private string typeToLoad => _objectTypeResolver.TypeFor(); - - public async Task StartAsync() - { - try - { - _logPresenter.ClearLog(); - _view.EnableButtons(false); - _logger.AddInfo(PKSimConstants.Information.LoadingSnapshot(_loadFromSnapshotDTO.SnapshotFile, typeToLoad)); - await Task.Run(performLoadAsync); - _logger.AddInfo(PKSimConstants.Information.SnapshotLoaded(typeToLoad)); - } - catch (Exception e) - { - _logger.AddException(e); - } - finally - { - //Start is disabled if the model was loaded successfully - _view.EnableButtons(cancelEnabled: true, okEnabled: ModelIsDefined, startEnabled: !ModelIsDefined); - } - } - - public bool ModelIsDefined => _model != null; - - public string SnapshotFile => _loadFromSnapshotDTO.SnapshotFile; - - private async Task performLoadAsync() - { - ClearModel(); - _model = await LoadModelAsync(_loadFromSnapshotDTO); - } - - protected virtual void ClearModel() - { - ClearModel(_model); - _model = null; - } - - protected virtual void ClearModel(IEnumerable model) - { - /*override if something needs to be done for specific loading case*/ - } - - protected virtual Task> LoadModelAsync(LoadFromSnapshotDTO loadFromSnapshotDTO) - { - return _snapshotTask.LoadModelsFromSnapshotFileAsync(loadFromSnapshotDTO.SnapshotFile); - } - - protected override void Cleanup() + IEventPublisher eventPublisher) : base(view, logPresenter, snapshotTask, dialogCreator, objectTypeResolver, logger, eventPublisher) { - try - { - ReleaseFrom(_eventPublisher); - } - finally - { - base.Cleanup(); - } } } } \ No newline at end of file diff --git a/src/PKSim.Presentation/Presenters/Snapshots/LoadProjectFromSnapshotPresenter.cs b/src/PKSim.Presentation/Presenters/Snapshots/LoadProjectFromSnapshotPresenter.cs index 168ecadda..8809669c5 100644 --- a/src/PKSim.Presentation/Presenters/Snapshots/LoadProjectFromSnapshotPresenter.cs +++ b/src/PKSim.Presentation/Presenters/Snapshots/LoadProjectFromSnapshotPresenter.cs @@ -1,31 +1,29 @@ using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; -using OSPSuite.Core; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Services; using OSPSuite.Presentation.Presenters; +using OSPSuite.Presentation.Views; using OSPSuite.Utility.Events; using PKSim.Core.Model; using PKSim.Core.Services; +using PKSim.Core.Snapshots; using PKSim.Core.Snapshots.Services; -using PKSim.Presentation.DTO.Snapshots; -using PKSim.Presentation.Views.Snapshots; +using QualificationPlan = OSPSuite.Core.Domain.QualificationPlan; namespace PKSim.Presentation.Presenters.Snapshots { public interface ILoadProjectFromSnapshotPresenter : ILoadFromSnapshotPresenter { /// - /// Project loaded from selected snapshot file. It is null if the user cancels the action or if the file was not loaded properly + /// Project loaded from selected snapshot file. It is null if the user cancels the action or if the file was not loaded + /// properly /// PKSimProject LoadProject(); - } - public class LoadProjectFromSnapshotPresenter : LoadFromSnapshotPresenter, ILoadProjectFromSnapshotPresenter + public class LoadProjectFromSnapshotPresenter : LoadProjectFromSnapshotPresenter, ILoadProjectFromSnapshotPresenter { - private readonly IQualiticationPlanRunner _qualificationPlanRunner; private readonly IRegistrationTask _registrationTask; public LoadProjectFromSnapshotPresenter(ILoadFromSnapshotView view, @@ -35,43 +33,25 @@ public LoadProjectFromSnapshotPresenter(ILoadFromSnapshotView view, IObjectTypeResolver objectTypeResolver, IOSPSuiteLogger logger, IEventPublisher eventPublisher, - IQualiticationPlanRunner qualificationPlanRunner, - IRegistrationTask registrationTask) : base(view, logPresenter, snapshotTask, dialogCreator, objectTypeResolver, logger, eventPublisher) + IQualificationPlanRunner qualificationPlanRunner, + IRegistrationTask registrationTask) : base(view, logPresenter, snapshotTask, dialogCreator, objectTypeResolver, logger, eventPublisher, qualificationPlanRunner) { - _qualificationPlanRunner = qualificationPlanRunner; _registrationTask = registrationTask; } - public PKSimProject LoadProject() + protected override IReadOnlyList AllQualificationPlansFrom(PKSimProject project) { - var models = LoadModelFromSnapshot(); - return models?.FirstOrDefault(); + return project.AllQualificationPlans.ToList(); } - protected override async Task> LoadModelAsync(LoadFromSnapshotDTO loadFromSnapshotDTO) + protected override void RegisterProject(PKSimProject project) { - var project = await _snapshotTask.LoadProjectFromSnapshotFileAsync(loadFromSnapshotDTO.SnapshotFile, loadFromSnapshotDTO.RunSimulations); _registrationTask.RegisterProject(project); - await runQualificationPlans(project); - return new[] { project }; } - protected override void ClearModel(IEnumerable model) - { - var projects = model?.ToList(); - base.ClearModel(projects); - _registrationTask.UnregisterProject(projectFrom(projects)); - } - - private PKSimProject projectFrom(IEnumerable projects) => projects?.FirstOrDefault(); - - private async Task runQualificationPlans(PKSimProject project) + protected override void UnRegisterProjects(List projects) { - //needs to be done sequentially - foreach (var qualificationPlan in project.AllQualificationPlans) - { - await _qualificationPlanRunner.RunAsync(qualificationPlan); - } + _registrationTask.UnregisterProject(ProjectFrom(projects)); } } } \ No newline at end of file diff --git a/src/PKSim.Presentation/Presenters/Snapshots/LoadSimulationFromSnapshotPresenter.cs b/src/PKSim.Presentation/Presenters/Snapshots/LoadSimulationFromSnapshotPresenter.cs index 5e98b8b6b..49d7f3df2 100644 --- a/src/PKSim.Presentation/Presenters/Snapshots/LoadSimulationFromSnapshotPresenter.cs +++ b/src/PKSim.Presentation/Presenters/Snapshots/LoadSimulationFromSnapshotPresenter.cs @@ -1,18 +1,17 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using OSPSuite.Core; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Services; +using OSPSuite.Presentation.DTO; using OSPSuite.Presentation.Presenters; +using OSPSuite.Presentation.Views; using OSPSuite.Utility.Events; using PKSim.Core; using PKSim.Core.Model; using PKSim.Core.Services; using PKSim.Core.Snapshots.Mappers; using PKSim.Core.Snapshots.Services; -using PKSim.Presentation.DTO.Snapshots; -using PKSim.Presentation.Views.Snapshots; namespace PKSim.Presentation.Presenters.Snapshots { diff --git a/src/PKSim.Presentation/Repositories/ButtonGroupRepository.cs b/src/PKSim.Presentation/Repositories/ButtonGroupRepository.cs index d318fd401..de2732c34 100644 --- a/src/PKSim.Presentation/Repositories/ButtonGroupRepository.cs +++ b/src/PKSim.Presentation/Repositories/ButtonGroupRepository.cs @@ -59,11 +59,11 @@ protected override IEnumerable AllButtonGroups() .WithButton(CreateRibbonButton.From(_menuBarItemRepository.Find(MenuBarItemIds.ProjectDescription))) .WithButton( CreateRibbonButton.From(_menuBarItemRepository.Find(MenuBarItemIds.ExportProjectToSnapshot)) - .WithCaption(PKSimConstants.MenuNames.ExportProjectToSnapshotMenu) + .WithCaption(MenuNames.ExportProjectToSnapshotMenu) ) .WithButton( CreateRibbonButton.From(_menuBarItemRepository.Find(MenuBarItemIds.LoadProjectFromSnahpshot)) - .WithCaption(PKSimConstants.MenuNames.LoadProjectFromSnapshotMenu) + .WithCaption(MenuNames.LoadProjectFromSnapshotMenu) ) .WithButton(CreateRibbonButton.From(_menuBarItemRepository.Find(MenuBarItemIds.SelectJournal))) .WithButton(CreateRibbonButton.From(_menuBarItemRepository.Find(MenuBarItemIds.About)).AsGroupStarter()) diff --git a/src/PKSim.Presentation/Repositories/MenuBarItemRepository.cs b/src/PKSim.Presentation/Repositories/MenuBarItemRepository.cs index 6c64d9cee..ab44423d5 100644 --- a/src/PKSim.Presentation/Repositories/MenuBarItemRepository.cs +++ b/src/PKSim.Presentation/Repositories/MenuBarItemRepository.cs @@ -42,16 +42,16 @@ protected override IEnumerable AllMenuBarItems() .WithIcon(ApplicationIcons.ProjectDescription) .WithShortcut(Keys.Control | Keys.D); - yield return CreateMenuButton.WithCaption(PKSimConstants.MenuNames.ExportProjectToSnapshot) + yield return CreateMenuButton.WithCaption(MenuNames.ExportProjectToSnapshot) .WithId(MenuBarItemIds.ExportProjectToSnapshot) - .WithCommand(_container) - .WithDescription(PKSimConstants.UI.ExportProjectToSnapshotDescription) + .WithCommand(_container) + .WithDescription(Captions.ExportProjectToSnapshotDescription) .WithIcon(ApplicationIcons.SnapshotExport); - yield return CreateMenuButton.WithCaption(PKSimConstants.MenuNames.LoadProjectFromSnapshot) + yield return CreateMenuButton.WithCaption(MenuNames.LoadProjectFromSnapshot) .WithId(MenuBarItemIds.LoadProjectFromSnahpshot) .WithCommand(_container) - .WithDescription(PKSimConstants.UI.LoadProjectFromSnapshotDescription) + .WithDescription(Captions.LoadProjectFromSnapshotDescription) .WithIcon(ApplicationIcons.SnapshotImport); yield return CreateMenuButton.WithCaption(PKSimConstants.MenuNames.CloseProject) diff --git a/src/PKSim.Presentation/Services/BuildingBlockTask.cs b/src/PKSim.Presentation/Services/BuildingBlockTask.cs index bff82ed21..4b69063cd 100644 --- a/src/PKSim.Presentation/Services/BuildingBlockTask.cs +++ b/src/PKSim.Presentation/Services/BuildingBlockTask.cs @@ -7,6 +7,7 @@ using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Services; using OSPSuite.Presentation.Core; +using OSPSuite.Presentation.Presenters; using OSPSuite.Presentation.Services; using OSPSuite.Utility; using OSPSuite.Utility.Collections; @@ -18,8 +19,6 @@ using PKSim.Core.Repositories; using PKSim.Core.Services; using PKSim.Presentation.Presenters; -using PKSim.Presentation.Presenters.Snapshots; -using ILazyLoadTask = PKSim.Core.Services.ILazyLoadTask; namespace PKSim.Presentation.Services { @@ -44,7 +43,6 @@ public BuildingBlockTask(IExecutionContext executionContext, ITemplateTaskQuery templateTaskQuery, ISingleStartPresenterTask singleStartPresenterTask, IBuildingBlockRepository buildingBlockRepository, - ILazyLoadTask lazyLoadTask, IPresentationSettingsTask presentationSettingsTask, ISimulationReferenceUpdater simulationReferenceUpdater) { @@ -137,7 +135,7 @@ public bool Delete(IReadOnlyList buildingBlocksT public bool Delete(TBuildingBlock buildingBlockToDelete) where TBuildingBlock : class, IPKSimBuildingBlock { - return Delete(new[] {buildingBlockToDelete}); + return Delete(new[] { buildingBlockToDelete }); } public IPKSimCommand DeleteCommand(TBuildingBlock buildingBlockToDelete) where TBuildingBlock : class, IPKSimBuildingBlock diff --git a/src/PKSim.Presentation/Services/ProjectTask.cs b/src/PKSim.Presentation/Services/ProjectTask.cs index 7d7e20eae..0be09d63a 100644 --- a/src/PKSim.Presentation/Services/ProjectTask.cs +++ b/src/PKSim.Presentation/Services/ProjectTask.cs @@ -31,8 +31,6 @@ public interface IProjectTask : OSPSuite.Presentation.Services.IProjectTask bool SaveCurrentProjectAs(); void OpenProject(); void Run(StartOptions startOptions); - void LoadProjectFromSnapshot(); - Task ExportCurrentProjectToSnapshot(); } public class ProjectTask : IProjectTask @@ -59,7 +57,7 @@ public ProjectTask(IWorkspace workspace, IJournalTask journalTask, IJournalRetriever journalRetriever, ISnapshotTask snapshotTask, - IBuildingBlockInProjectManager buildingBlockInProjectManager + IBuildingBlockInProjectManager buildingBlockInProjectManager ) { _workspace = workspace; @@ -226,7 +224,6 @@ public void LoadProjectFromSnapshot() { if (!shouldCloseProject()) return; - using (var presenter = _applicationController.Start()) { var project = presenter.LoadProject(); @@ -250,7 +247,7 @@ public Task ExportCurrentProjectToSnapshot() if (exitIf(anySimulationInChangedState && projectExportWillCreateNoise, PKSimConstants.UI.SnapshotOfProjectCreatedWithEarlierVersionAndWithChangedSimulation)) return Task.CompletedTask; - if (exitIf(anySimulationInChangedState && !projectExportWillCreateNoise, PKSimConstants.UI.SnapshotOfProjectWithChangedSimulation)) + if (exitIf(anySimulationInChangedState && !projectExportWillCreateNoise, Captions.SnapshotOfProjectWithChangedSimulation)) return Task.CompletedTask; if (exitIf(!anySimulationInChangedState && projectExportWillCreateNoise, PKSimConstants.UI.SnapshotOfProjectCreatedWithEarlierVersion)) diff --git a/src/PKSim.Presentation/UICommands/ExportProjectToSnapshotCommand.cs b/src/PKSim.Presentation/UICommands/ExportProjectToSnapshotCommand.cs deleted file mode 100644 index 3383f5217..000000000 --- a/src/PKSim.Presentation/UICommands/ExportProjectToSnapshotCommand.cs +++ /dev/null @@ -1,21 +0,0 @@ -using OSPSuite.Core.Extensions; -using OSPSuite.Presentation.MenuAndBars; -using PKSim.Presentation.Services; - -namespace PKSim.Presentation.UICommands -{ - public class ExportProjectToSnapshotCommand : IUICommand - { - private readonly IProjectTask _projectTask; - - public ExportProjectToSnapshotCommand(IProjectTask projectTask) - { - _projectTask = projectTask; - } - - public async void Execute() - { - await _projectTask.SecureAwait(x => x.ExportCurrentProjectToSnapshot()); - } - } -} \ No newline at end of file diff --git a/src/PKSim.Presentation/UICommands/LoadProjectFromSnapshotUICommand.cs b/src/PKSim.Presentation/UICommands/LoadProjectFromSnapshotUICommand.cs deleted file mode 100644 index 802d280bd..000000000 --- a/src/PKSim.Presentation/UICommands/LoadProjectFromSnapshotUICommand.cs +++ /dev/null @@ -1,20 +0,0 @@ -using OSPSuite.Presentation.MenuAndBars; -using PKSim.Presentation.Services; - -namespace PKSim.Presentation.UICommands -{ - public class LoadProjectFromSnapshotUICommand : IUICommand - { - private readonly IProjectTask _projectTask; - - public LoadProjectFromSnapshotUICommand(IProjectTask projectTask) - { - _projectTask = projectTask; - } - - public void Execute() - { - _projectTask.LoadProjectFromSnapshot(); - } - } -} \ No newline at end of file diff --git a/src/PKSim.Presentation/Views/Snapshots/ILoadFromSnapshotView.cs b/src/PKSim.Presentation/Views/Snapshots/ILoadFromSnapshotView.cs deleted file mode 100644 index b1237b1d7..000000000 --- a/src/PKSim.Presentation/Views/Snapshots/ILoadFromSnapshotView.cs +++ /dev/null @@ -1,13 +0,0 @@ -using OSPSuite.Presentation.Views; -using PKSim.Presentation.DTO.Snapshots; -using PKSim.Presentation.Presenters.Snapshots; - -namespace PKSim.Presentation.Views.Snapshots -{ - public interface ILoadFromSnapshotView : IModalView - { - void AddLogView(IView view); - void BindTo(LoadFromSnapshotDTO loadFromSnapshotDTO); - void EnableButtons(bool cancelEnabled, bool okEnabled = false, bool startEnabled=false); - } -} \ No newline at end of file diff --git a/src/PKSim.R/PKSim.R.csproj b/src/PKSim.R/PKSim.R.csproj index 6322d8993..447c61eb5 100644 --- a/src/PKSim.R/PKSim.R.csproj +++ b/src/PKSim.R/PKSim.R.csproj @@ -41,9 +41,9 @@ - + - + diff --git a/src/PKSim.UI.Starter/PKSim.UI.Starter.csproj b/src/PKSim.UI.Starter/PKSim.UI.Starter.csproj index 1ae6e7152..9660daeef 100644 --- a/src/PKSim.UI.Starter/PKSim.UI.Starter.csproj +++ b/src/PKSim.UI.Starter/PKSim.UI.Starter.csproj @@ -19,10 +19,10 @@ - - - - + + + + diff --git a/src/PKSim.UI/PKSim.UI.csproj b/src/PKSim.UI/PKSim.UI.csproj index 6b2d433ee..23d7b75fe 100644 --- a/src/PKSim.UI/PKSim.UI.csproj +++ b/src/PKSim.UI/PKSim.UI.csproj @@ -10,6 +10,7 @@ bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml 1591 13.0.0 + true @@ -55,14 +56,14 @@ - + - - - + + + diff --git a/src/PKSim.UI/Views/Simulations/ImportPopulationSimulationView.cs b/src/PKSim.UI/Views/Simulations/ImportPopulationSimulationView.cs index fb89d7ce0..21f8ec42b 100644 --- a/src/PKSim.UI/Views/Simulations/ImportPopulationSimulationView.cs +++ b/src/PKSim.UI/Views/Simulations/ImportPopulationSimulationView.cs @@ -1,20 +1,20 @@ using System; using System.Windows.Forms; +using DevExpress.XtraEditors.Controls; +using DevExpress.XtraLayout.Utils; +using OSPSuite.Assets; using OSPSuite.DataBinding; using OSPSuite.DataBinding.DevExpress; -using OSPSuite.Assets; +using OSPSuite.Presentation.Extensions; +using OSPSuite.UI.Extensions; +using OSPSuite.UI.Views; using OSPSuite.Utility.Collections; using OSPSuite.Utility.Extensions; -using DevExpress.XtraEditors.Controls; -using DevExpress.XtraLayout.Utils; using PKSim.Assets; using PKSim.Presentation.DTO.Simulations; using PKSim.Presentation.Presenters.Simulations; using PKSim.Presentation.Views.Simulations; using PKSim.UI.Extensions; -using OSPSuite.Presentation.Extensions; -using OSPSuite.UI.Extensions; -using OSPSuite.UI.Views; namespace PKSim.UI.Views.Simulations { @@ -76,7 +76,7 @@ public bool SimulationSelectionVisible public override void InitializeBinding() { - panelBuildingBlockSelection.FillWith((Control) _uxPopulationSelection); + panelBuildingBlockSelection.FillWith((Control)_uxPopulationSelection); _screenBinder.Bind(x => x.Population) .To(_uxPopulationSelection); @@ -148,7 +148,7 @@ public override void InitializeResources() layoutItemSimulationFileSelection.Text = PKSimConstants.UI.SimulationFilePath.FormatForLabel(); layoutItemPopulationFileSelection.Text = PKSimConstants.UI.PopulationFilePath.FormatForLabel(); layoutItemNumberOfIndividuals.Text = PKSimConstants.UI.NumberOfIndividuals.FormatForLabel(); - btnStartImport.InitWithImage(ApplicationIcons.Run, text: PKSimConstants.UI.StartImport); + btnStartImport.InitWithImage(ApplicationIcons.Run, text: Captions.StartImport); layoutItemButtonImport.AdjustLargeButtonSize(layoutControl); layoutControlGroupSimulationFileSelection.Text = PKSimConstants.ObjectTypes.Simulation; diff --git a/src/PKSim.UI/Views/Simulations/ImportSimulationPKAnalysesView.cs b/src/PKSim.UI/Views/Simulations/ImportSimulationPKAnalysesView.cs index dc4ab9fd4..6d9414cf5 100644 --- a/src/PKSim.UI/Views/Simulations/ImportSimulationPKAnalysesView.cs +++ b/src/PKSim.UI/Views/Simulations/ImportSimulationPKAnalysesView.cs @@ -75,7 +75,7 @@ public override void InitializeResources() base.InitializeResources(); layoutItemSelectFileToImport.Text = PKSimConstants.UI.FilePath.FormatForLabel(); - btnImport.InitWithImage(ApplicationIcons.Run, text: PKSimConstants.UI.StartImport); + btnImport.InitWithImage(ApplicationIcons.Run, text: Captions.StartImport); layoutItemButtonImport.AdjustLargeButtonSize(layoutControl); tbFileToImport.Properties.TextEditStyle = TextEditStyles.DisableTextEditor; diff --git a/src/PKSim.UI/Views/Simulations/ImportSimulationResultsView.cs b/src/PKSim.UI/Views/Simulations/ImportSimulationResultsView.cs index 91ef2a4f6..92c8f266b 100644 --- a/src/PKSim.UI/Views/Simulations/ImportSimulationResultsView.cs +++ b/src/PKSim.UI/Views/Simulations/ImportSimulationResultsView.cs @@ -139,7 +139,7 @@ public override void InitializeResources() btnAddFile.InitWithImage(ApplicationIcons.Create, text: PKSimConstants.UI.AddFile); layoutItemButtonAdd.AdjustLargeButtonSize(layoutControl); - btnImport.InitWithImage(ApplicationIcons.Run, text: PKSimConstants.UI.StartImport); + btnImport.InitWithImage(ApplicationIcons.Run, text: Captions.StartImport); layoutItemButtonImport.AdjustLargeButtonSize(layoutControl); layoutGroupImportFolder.Text = PKSimConstants.UI.ImportFolder; diff --git a/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.Designer.cs b/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.Designer.cs deleted file mode 100644 index ea25cde88..000000000 --- a/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.Designer.cs +++ /dev/null @@ -1,213 +0,0 @@ -namespace PKSim.UI.Views.Snapshots -{ - partial class LoadFromSnapshotView - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - _screenBinder.Dispose(); - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.layoutControl = new OSPSuite.UI.Controls.UxLayoutControl(); - this.buttonStart = new DevExpress.XtraEditors.SimpleButton(); - this.logPanel = new DevExpress.XtraEditors.PanelControl(); - this.buttonEditSelectSnapshot = new DevExpress.XtraEditors.ButtonEdit(); - this.layoutControlGroup = new DevExpress.XtraLayout.LayoutControlGroup(); - this.layoutItemButtonSelectSnapshot = new DevExpress.XtraLayout.LayoutControlItem(); - this.layoutItemLogPanel = new DevExpress.XtraLayout.LayoutControlItem(); - this.layoutItemStartButton = new DevExpress.XtraLayout.LayoutControlItem(); - this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem(); - this.chkRunSimulations = new DevExpress.XtraEditors.CheckEdit(); - this.layoutItemRunSimulations = new DevExpress.XtraLayout.LayoutControlItem(); - ((System.ComponentModel.ISupportInitialize)(this.tablePanel)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this._errorProvider)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutControl)).BeginInit(); - this.layoutControl.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.logPanel)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.buttonEditSelectSnapshot.Properties)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutItemButtonSelectSnapshot)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutItemLogPanel)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutItemStartButton)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.chkRunSimulations.Properties)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutItemRunSimulations)).BeginInit(); - this.SuspendLayout(); - // - // tablePanel - // - this.tablePanel.Location = new System.Drawing.Point(0, 581); - this.tablePanel.Size = new System.Drawing.Size(769, 43); - // - // layoutControl - // - this.layoutControl.AllowCustomization = false; - this.layoutControl.Controls.Add(this.chkRunSimulations); - this.layoutControl.Controls.Add(this.buttonStart); - this.layoutControl.Controls.Add(this.logPanel); - this.layoutControl.Controls.Add(this.buttonEditSelectSnapshot); - this.layoutControl.Dock = System.Windows.Forms.DockStyle.Fill; - this.layoutControl.Location = new System.Drawing.Point(0, 0); - this.layoutControl.Name = "layoutControl"; - this.layoutControl.Root = this.layoutControlGroup; - this.layoutControl.Size = new System.Drawing.Size(769, 581); - this.layoutControl.TabIndex = 38; - this.layoutControl.Text = "layoutControl1"; - // - // buttonStart - // - this.buttonStart.Location = new System.Drawing.Point(386, 547); - this.buttonStart.Name = "buttonStart"; - this.buttonStart.Size = new System.Drawing.Size(371, 22); - this.buttonStart.StyleController = this.layoutControl; - this.buttonStart.TabIndex = 6; - this.buttonStart.Text = "buttonStart"; - // - // logPanel - // - this.logPanel.Location = new System.Drawing.Point(12, 60); - this.logPanel.Name = "logPanel"; - this.logPanel.Size = new System.Drawing.Size(745, 483); - this.logPanel.TabIndex = 5; - // - // buttonEditSelectSnapshot - // - this.buttonEditSelectSnapshot.Location = new System.Drawing.Point(182, 12); - this.buttonEditSelectSnapshot.Name = "buttonEditSelectSnapshot"; - this.buttonEditSelectSnapshot.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { - new DevExpress.XtraEditors.Controls.EditorButton()}); - this.buttonEditSelectSnapshot.Size = new System.Drawing.Size(575, 20); - this.buttonEditSelectSnapshot.StyleController = this.layoutControl; - this.buttonEditSelectSnapshot.TabIndex = 4; - // - // layoutControlGroup - // - this.layoutControlGroup.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True; - this.layoutControlGroup.GroupBordersVisible = false; - this.layoutControlGroup.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { - this.layoutItemButtonSelectSnapshot, - this.layoutItemLogPanel, - this.layoutItemStartButton, - this.emptySpaceItem1, - this.layoutItemRunSimulations}); - this.layoutControlGroup.Name = "layoutControlGroup"; - this.layoutControlGroup.Size = new System.Drawing.Size(769, 581); - this.layoutControlGroup.TextVisible = false; - // - // layoutItemButtonSelectSnapshot - // - this.layoutItemButtonSelectSnapshot.Control = this.buttonEditSelectSnapshot; - this.layoutItemButtonSelectSnapshot.Location = new System.Drawing.Point(0, 0); - this.layoutItemButtonSelectSnapshot.Name = "layoutItemButtonSelectSnapshot"; - this.layoutItemButtonSelectSnapshot.Size = new System.Drawing.Size(749, 24); - this.layoutItemButtonSelectSnapshot.TextSize = new System.Drawing.Size(158, 13); - // - // layoutItemLogPanel - // - this.layoutItemLogPanel.Control = this.logPanel; - this.layoutItemLogPanel.Location = new System.Drawing.Point(0, 48); - this.layoutItemLogPanel.Name = "layoutItemLogPanel"; - this.layoutItemLogPanel.Size = new System.Drawing.Size(749, 487); - this.layoutItemLogPanel.TextSize = new System.Drawing.Size(0, 0); - this.layoutItemLogPanel.TextVisible = false; - // - // layoutItemStartButton - // - this.layoutItemStartButton.Control = this.buttonStart; - this.layoutItemStartButton.Location = new System.Drawing.Point(374, 535); - this.layoutItemStartButton.Name = "layoutItemStartButton"; - this.layoutItemStartButton.Size = new System.Drawing.Size(375, 26); - this.layoutItemStartButton.TextSize = new System.Drawing.Size(0, 0); - this.layoutItemStartButton.TextVisible = false; - // - // emptySpaceItem1 - // - this.emptySpaceItem1.AllowHotTrack = false; - this.emptySpaceItem1.Location = new System.Drawing.Point(0, 535); - this.emptySpaceItem1.Name = "emptySpaceItem1"; - this.emptySpaceItem1.Size = new System.Drawing.Size(374, 26); - this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0); - // - // chkRunSimulations - // - this.chkRunSimulations.Location = new System.Drawing.Point(12, 36); - this.chkRunSimulations.Name = "chkRunSimulations"; - this.chkRunSimulations.Properties.Caption = "chkRunSimulations"; - this.chkRunSimulations.Size = new System.Drawing.Size(745, 20); - this.chkRunSimulations.StyleController = this.layoutControl; - this.chkRunSimulations.TabIndex = 0; - // - // layoutControlItem1 - // - this.layoutItemRunSimulations.Control = this.chkRunSimulations; - this.layoutItemRunSimulations.Location = new System.Drawing.Point(0, 24); - this.layoutItemRunSimulations.Name = "layoutItemRunSimulations"; - this.layoutItemRunSimulations.Size = new System.Drawing.Size(749, 24); - this.layoutItemRunSimulations.TextSize = new System.Drawing.Size(0, 0); - this.layoutItemRunSimulations.TextVisible = false; - // - // LoadFromSnapshotView - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Caption = "LoadFromSnapshotView"; - this.ClientSize = new System.Drawing.Size(769, 624); - this.Controls.Add(this.layoutControl); - this.Name = "LoadFromSnapshotView"; - this.Text = "LoadFromSnapshotView"; - this.Controls.SetChildIndex(this.tablePanel, 0); - this.Controls.SetChildIndex(this.layoutControl, 0); - ((System.ComponentModel.ISupportInitialize)(this.tablePanel)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this._errorProvider)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutControl)).EndInit(); - this.layoutControl.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)(this.logPanel)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.buttonEditSelectSnapshot.Properties)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutItemButtonSelectSnapshot)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutItemLogPanel)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutItemStartButton)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.chkRunSimulations.Properties)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.layoutItemRunSimulations)).EndInit(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private OSPSuite.UI.Controls.UxLayoutControl layoutControl; - private DevExpress.XtraEditors.PanelControl logPanel; - private DevExpress.XtraEditors.ButtonEdit buttonEditSelectSnapshot; - private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup; - private DevExpress.XtraLayout.LayoutControlItem layoutItemButtonSelectSnapshot; - private DevExpress.XtraLayout.LayoutControlItem layoutItemLogPanel; - private DevExpress.XtraEditors.SimpleButton buttonStart; - private DevExpress.XtraLayout.LayoutControlItem layoutItemStartButton; - private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1; - private DevExpress.XtraEditors.CheckEdit chkRunSimulations; - private DevExpress.XtraLayout.LayoutControlItem layoutItemRunSimulations; - } -} \ No newline at end of file diff --git a/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.cs b/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.cs deleted file mode 100644 index 4858f4524..000000000 --- a/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.cs +++ /dev/null @@ -1,90 +0,0 @@ -using OSPSuite.Assets; -using OSPSuite.DataBinding; -using OSPSuite.DataBinding.DevExpress; -using OSPSuite.Presentation.Extensions; -using OSPSuite.Presentation.Views; -using OSPSuite.UI.Extensions; -using OSPSuite.UI.Views; -using PKSim.Assets; -using PKSim.Presentation.DTO.Snapshots; -using PKSim.Presentation.Presenters.Snapshots; -using PKSim.Presentation.Views.Snapshots; - -namespace PKSim.UI.Views.Snapshots -{ - public partial class LoadFromSnapshotView : BaseModalView, ILoadFromSnapshotView - { - private ILoadFromSnapshotPresenter _presenter; - private readonly ScreenBinder _screenBinder = new ScreenBinder(); - - //only for design time - public LoadFromSnapshotView() : this(null) - { - } - - public LoadFromSnapshotView(IShell shell) : base(shell) - { - InitializeComponent(); - } - - public override void InitializeBinding() - { - base.InitializeBinding(); - - _screenBinder.Bind(x => x.SnapshotFile) - .To(buttonEditSelectSnapshot); - - _screenBinder.Bind(x => x.RunSimulations) - .To(chkRunSimulations) - .WithCaption(PKSimConstants.UI.RunSimulations); - - buttonEditSelectSnapshot.ButtonClick += (o, e) => OnEvent(() => _presenter.SelectFile()); - buttonStart.Click += (o, e) => OnEvent(() => _presenter.StartAsync()); - - RegisterValidationFor(_screenBinder); - } - - public void AttachPresenter(ILoadFromSnapshotPresenter presenter) - { - _presenter = presenter; - } - - public void AddLogView(IView view) - { - logPanel.FillWith(view); - } - - public void BindTo(LoadFromSnapshotDTO loadFromSnapshotDTO) - { - _screenBinder.BindToSource(loadFromSnapshotDTO); - } - - public void EnableButtons(bool cancelEnabled, bool okEnabled = false, bool startEnabled = false) - { - OkEnabled = okEnabled; - CancelEnabled = cancelEnabled; - buttonStart.Enabled = startEnabled; - } - - protected override void SetOkButtonEnable() - { - base.SetOkButtonEnable(); - buttonStart.Enabled = !HasError; - } - - protected override bool IsOkButtonEnable => _presenter.ModelIsDefined; - - public override void InitializeResources() - { - base.InitializeResources(); - layoutItemStartButton.AdjustLargeButtonSize(layoutControl); - buttonStart.InitWithImage(ApplicationIcons.Run, PKSimConstants.UI.StartImport); - layoutItemButtonSelectSnapshot.Text = PKSimConstants.UI.SnapshotFile.FormatForLabel(); - ApplicationIcon = ApplicationIcons.Snapshot; - } - - public override bool HasError => _screenBinder.HasError; - - protected override bool ShouldClose => _presenter.ShouldClose; - } -} \ No newline at end of file diff --git a/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.resx b/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.resx deleted file mode 100644 index 91f678938..000000000 --- a/src/PKSim.UI/Views/Snapshots/LoadFromSnapshotView.resx +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - \ No newline at end of file diff --git a/src/PKSim/PKSim.csproj b/src/PKSim/PKSim.csproj index 8060d4115..bed7e7e08 100644 --- a/src/PKSim/PKSim.csproj +++ b/src/PKSim/PKSim.csproj @@ -72,14 +72,14 @@ - - + + - + diff --git a/src/PKSimRDependencyResolution/PKSimRDependencyResolution.csproj b/src/PKSimRDependencyResolution/PKSimRDependencyResolution.csproj index c18f978fb..5e85eeaa1 100644 --- a/src/PKSimRDependencyResolution/PKSimRDependencyResolution.csproj +++ b/src/PKSimRDependencyResolution/PKSimRDependencyResolution.csproj @@ -20,7 +20,7 @@ - + diff --git a/tests/PKSim.R.Tests/PKSim.R.Tests.csproj b/tests/PKSim.R.Tests/PKSim.R.Tests.csproj index e8912678b..72c563248 100644 --- a/tests/PKSim.R.Tests/PKSim.R.Tests.csproj +++ b/tests/PKSim.R.Tests/PKSim.R.Tests.csproj @@ -17,9 +17,9 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - + - + diff --git a/tests/PKSim.Tests/Core/ClassificationSnapshotTaskSpecs.cs b/tests/PKSim.Tests/Core/ClassificationSnapshotTaskSpecs.cs index 6f7c019a1..6bf2f5578 100644 --- a/tests/PKSim.Tests/Core/ClassificationSnapshotTaskSpecs.cs +++ b/tests/PKSim.Tests/Core/ClassificationSnapshotTaskSpecs.cs @@ -5,8 +5,10 @@ using OSPSuite.BDDHelper.Extensions; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Data; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Model; using PKSim.Core.Snapshots.Mappers; +using SnapshotContext = PKSim.Core.Snapshots.Mappers.SnapshotContext; namespace PKSim.Core { diff --git a/tests/PKSim.Tests/Core/ProjectMapperSpecs.cs b/tests/PKSim.Tests/Core/ProjectMapperSpecs.cs index 58ceabe92..203c3a672 100644 --- a/tests/PKSim.Tests/Core/ProjectMapperSpecs.cs +++ b/tests/PKSim.Tests/Core/ProjectMapperSpecs.cs @@ -7,6 +7,7 @@ using OSPSuite.BDDHelper.Extensions; using OSPSuite.Core.Domain; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Chart; using PKSim.Core.Model; using PKSim.Core.Services; @@ -23,8 +24,9 @@ using Population = PKSim.Core.Model.Population; using Project = PKSim.Core.Snapshots.Project; using Protocol = PKSim.Core.Model.Protocol; -using QualificationPlan = PKSim.Core.Model.QualificationPlan; +using QualificationPlan = OSPSuite.Core.Domain.QualificationPlan; using Simulation = PKSim.Core.Snapshots.Simulation; +using SnapshotContext = PKSim.Core.Snapshots.Mappers.SnapshotContext; namespace PKSim.Core { diff --git a/tests/PKSim.Tests/Core/ProjectSnapshotToSimulationMapperSpecs.cs b/tests/PKSim.Tests/Core/ProjectSnapshotToSimulationMapperSpecs.cs index b7f914d62..bacd582e7 100644 --- a/tests/PKSim.Tests/Core/ProjectSnapshotToSimulationMapperSpecs.cs +++ b/tests/PKSim.Tests/Core/ProjectSnapshotToSimulationMapperSpecs.cs @@ -4,10 +4,12 @@ using OSPSuite.BDDHelper.Extensions; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Mappers; +using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Exceptions; using PKSim.Core.Model; using PKSim.Core.Services; -using PKSim.Core.Snapshots.Mappers; +using SnapshotContext = PKSim.Core.Snapshots.Mappers.SnapshotContext; namespace PKSim.Core { @@ -51,4 +53,4 @@ public void the_exception_should_be_thrown() The.Action(() => sut.MapFrom(_snapshotString)).ShouldThrowAn(); } } -} +} \ No newline at end of file diff --git a/tests/PKSim.Tests/Core/QualificationPlanMapperSpecs.cs b/tests/PKSim.Tests/Core/QualificationPlanMapperSpecs.cs index b77dce37b..dcc937257 100644 --- a/tests/PKSim.Tests/Core/QualificationPlanMapperSpecs.cs +++ b/tests/PKSim.Tests/Core/QualificationPlanMapperSpecs.cs @@ -6,7 +6,7 @@ using PKSim.Core.Model; using PKSim.Core.Snapshots; using PKSim.Core.Snapshots.Mappers; -using QualificationPlan = PKSim.Core.Model.QualificationPlan; +using QualificationPlan = OSPSuite.Core.Domain.QualificationPlan; namespace PKSim.Core { diff --git a/tests/PKSim.Tests/Core/SnapshotMapperSpecs.cs b/tests/PKSim.Tests/Core/SnapshotMapperSpecs.cs deleted file mode 100644 index 21f560d60..000000000 --- a/tests/PKSim.Tests/Core/SnapshotMapperSpecs.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using FakeItEasy; -using OSPSuite.BDDHelper; -using OSPSuite.BDDHelper.Extensions; -using OSPSuite.Utility.Collections; -using PKSim.Core.Snapshots; -using PKSim.Core.Snapshots.Mappers; -using PKSim.Extensions; - - -namespace PKSim.Core -{ - public abstract class concern_for_SnapshotMapper : ContextSpecificationAsync - { - private IRepository _snapshotMapperRepository; - protected ISnapshotMapperSpecification _snapshotMapper1; - protected ISnapshotMapperSpecification _snapshotMapper2; - - protected override Task Context() - { - _snapshotMapperRepository= A.Fake>(); - _snapshotMapper1= A.Fake(); - _snapshotMapper2= A.Fake(); - - A.CallTo(() => _snapshotMapperRepository.All()).Returns(new []{_snapshotMapper1, _snapshotMapper2, }); - - sut = new SnapshotMapper(_snapshotMapperRepository); - return Task.FromResult(true); - } - } - - public class When_mapping_an_object_for_a_which_a_snapshot_can_be_found_to_a_snapshot_object : concern_for_SnapshotMapper - { - private object _model; - private object _snapshot; - - protected override async Task Context() - { - await base.Context(); - _model = new Model.Formulation(); - _snapshot = new Snapshots.Formulation(); - A.CallTo(() => _snapshotMapper1.IsSatisfiedBy(_model.GetType())).Returns(false); - A.CallTo(() => _snapshotMapper2.IsSatisfiedBy(_model.GetType())).Returns(true); - A.CallTo(() => _snapshotMapper2.MapToSnapshot(_model)).Returns(_snapshot); - } - - protected override async Task Because() - { - _snapshot = await sut.MapToSnapshot(_model); - } - - [Observation] - public void should_return_the_expected_snapshot() - { - _snapshot.ShouldBeEqualTo(_snapshot); - } - } - - public class When_mapping_an_object_for_a_which_no_snapshot_can_be_found_to_a_snapshot_object : concern_for_SnapshotMapper - { - private object _model; - - protected override async Task Context() - { - await base.Context(); - _model = new Model.Formulation(); - } - - [Observation] - public void should_throw_a_no_mapper_can_be_found_exception() - { - The.Action(()=>sut.MapToSnapshot(_model)).ShouldThrowAn(); - } - } -} \ No newline at end of file diff --git a/tests/PKSim.Tests/Core/SnapshotTaskSpecs.cs b/tests/PKSim.Tests/Core/SnapshotTaskSpecs.cs index 35f8d15b6..a4d72b14b 100644 --- a/tests/PKSim.Tests/Core/SnapshotTaskSpecs.cs +++ b/tests/PKSim.Tests/Core/SnapshotTaskSpecs.cs @@ -8,12 +8,14 @@ using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using PKSim.Core.Model; using PKSim.Core.Services; using PKSim.Core.Snapshots.Mappers; using PKSim.Core.Snapshots.Services; using Parameter = PKSim.Core.Snapshots.Parameter; using Project = PKSim.Core.Snapshots.Project; +using SnapshotContext = PKSim.Core.Snapshots.Mappers.SnapshotContext; namespace PKSim.Core { diff --git a/tests/PKSim.Tests/Infrastructure/ObservedDataTaskSpecs.cs b/tests/PKSim.Tests/Infrastructure/ObservedDataTaskSpecs.cs index 2daa067ae..5b1f9cc4f 100644 --- a/tests/PKSim.Tests/Infrastructure/ObservedDataTaskSpecs.cs +++ b/tests/PKSim.Tests/Infrastructure/ObservedDataTaskSpecs.cs @@ -15,6 +15,7 @@ using OSPSuite.Core.Serialization.Xml; using OSPSuite.Core.Services; using OSPSuite.Presentation.Core; +using OSPSuite.Presentation.Presenters; using OSPSuite.Utility.Exceptions; using PKSim.Core; using PKSim.Core.Model; diff --git a/tests/PKSim.Tests/Infrastructure/SnapshotSerializerSpecs.cs b/tests/PKSim.Tests/Infrastructure/SnapshotSerializerSpecs.cs index 5bb93c35b..85d791653 100644 --- a/tests/PKSim.Tests/Infrastructure/SnapshotSerializerSpecs.cs +++ b/tests/PKSim.Tests/Infrastructure/SnapshotSerializerSpecs.cs @@ -6,15 +6,12 @@ using OSPSuite.BDDHelper; using OSPSuite.BDDHelper.Extensions; using OSPSuite.Utility; -using PKSim.Core.Services; using PKSim.Core.Snapshots; -using PKSim.Core.Snapshots.Services; using PKSim.Infrastructure.Serialization.Json; - namespace PKSim.Infrastructure { - public abstract class concern_for_SnapshotSerializer : ContextSpecificationAsync + public abstract class concern_for_SnapshotSerializer : ContextSpecificationAsync { protected Parameter _parameter; protected string _fileName; @@ -40,8 +37,7 @@ public override async Task GlobalCleanup() } } - - public class When_serializing_a_parameter_with_a_value_set: concern_for_SnapshotSerializer + public class When_serializing_a_parameter_with_a_value_set : concern_for_SnapshotSerializer { [TestCase(null)] [TestCase(1.123456789)] @@ -51,7 +47,7 @@ public class When_serializing_a_parameter_with_a_value_set: concern_for_Snapshot [TestCase(449.9999999999991, 450)] [TestCase(199.999998E-2)] [TestCase(199.999999998E-2, 2d)] - public async Task should_serialized_the_number_using_the_expected_precision(double? originalValue, double? expectedValue=null) + public async Task should_serialized_the_number_using_the_expected_precision(double? originalValue, double? expectedValue = null) { _parameter.Value = originalValue; await sut.Serialize(_parameter, _fileName); @@ -68,7 +64,7 @@ public class When_serializing_an_array_of_objects_to_json : concern_for_Snapshot protected override async Task Because() { - await sut.Serialize(new[] {_parameter, _parameter}, _fileName); + await sut.Serialize(new[] { _parameter, _parameter }, _fileName); _deserializedParameters = (await sut.DeserializeAsArray(_fileName, typeof(Parameter))).Cast(); } @@ -86,7 +82,6 @@ public class When_serializing_an_object_with_a_color_property : concern_for_Snap protected override async Task Context() { - await base.Context(); _curveOptions = new CurveOptions { @@ -114,7 +109,6 @@ public class When_serializing_an_object_with_a_color_property_with_transparency protected override async Task Context() { - await base.Context(); _curveOptions = new CurveOptions { diff --git a/tests/PKSim.Tests/IntegrationTests/ContextWithLoadedSnapshot.cs b/tests/PKSim.Tests/IntegrationTests/ContextWithLoadedSnapshot.cs index 5b84d97fc..e1b9d9b3b 100644 --- a/tests/PKSim.Tests/IntegrationTests/ContextWithLoadedSnapshot.cs +++ b/tests/PKSim.Tests/IntegrationTests/ContextWithLoadedSnapshot.cs @@ -2,10 +2,10 @@ using System.Linq; using NUnit.Framework; using OSPSuite.Core.Domain; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Container; using PKSim.Core; using PKSim.Core.Model; -using PKSim.Core.Snapshots.Mappers; using PKSim.Core.Snapshots.Services; namespace PKSim.IntegrationTests diff --git a/tests/PKSim.Tests/IntegrationTests/SimulationToProjectSnapshotMapperSpecs.cs b/tests/PKSim.Tests/IntegrationTests/SimulationToProjectSnapshotMapperSpecs.cs index d238de4f8..fcc117ca3 100644 --- a/tests/PKSim.Tests/IntegrationTests/SimulationToProjectSnapshotMapperSpecs.cs +++ b/tests/PKSim.Tests/IntegrationTests/SimulationToProjectSnapshotMapperSpecs.cs @@ -3,6 +3,8 @@ using OSPSuite.BDDHelper; using OSPSuite.BDDHelper.Extensions; using OSPSuite.Core.Domain; +using OSPSuite.Core.Services; +using OSPSuite.Core.Snapshots.Mappers; using OSPSuite.Utility.Container; using PKSim.Core; using PKSim.Core.Model; diff --git a/tests/PKSim.Tests/PKSim.Tests.csproj b/tests/PKSim.Tests/PKSim.Tests.csproj index f68a2df6d..9313a0c96 100644 --- a/tests/PKSim.Tests/PKSim.Tests.csproj +++ b/tests/PKSim.Tests/PKSim.Tests.csproj @@ -17,7 +17,7 @@ - + diff --git a/tests/PKSim.Tests/Presentation/BuildingBlockTaskSpecs.cs b/tests/PKSim.Tests/Presentation/BuildingBlockTaskSpecs.cs index fd4f4b3c1..2ddedf0ad 100644 --- a/tests/PKSim.Tests/Presentation/BuildingBlockTaskSpecs.cs +++ b/tests/PKSim.Tests/Presentation/BuildingBlockTaskSpecs.cs @@ -37,7 +37,6 @@ public abstract class concern_for_BuildingBlockTask : ContextSpecificationAsync< protected ITemplateTaskQuery _templateTaskQuery; protected ISingleStartPresenterTask _singleStartPresenterTask; protected IBuildingBlockRepository _buildingBlockRepository; - protected ILazyLoadTask _lazyLoadTask; protected ISimulationReferenceUpdater _simulationReferenceUpdater; protected IPresentationSettingsTask _presenterSettingsTask; @@ -55,7 +54,6 @@ protected override Task Context() _renamePresenter = A.Fake(); _dialogCreator = A.Fake(); _singleStartPresenterTask = A.Fake(); - _lazyLoadTask = A.Fake(); _presenterSettingsTask = A.Fake(); _simulationReferenceUpdater = A.Fake(); @@ -68,7 +66,6 @@ protected override Task Context() _templateTaskQuery, _singleStartPresenterTask, _buildingBlockRepository, - _lazyLoadTask, _presenterSettingsTask, _simulationReferenceUpdater); diff --git a/tests/PKSim.Tests/Presentation/ExportProjectToSnapshotCommandSpecs.cs b/tests/PKSim.Tests/Presentation/ExportProjectToSnapshotCommandSpecs.cs deleted file mode 100644 index 664c05b8b..000000000 --- a/tests/PKSim.Tests/Presentation/ExportProjectToSnapshotCommandSpecs.cs +++ /dev/null @@ -1,32 +0,0 @@ -using FakeItEasy; -using OSPSuite.BDDHelper; -using PKSim.Presentation.Services; -using PKSim.Presentation.UICommands; - -namespace PKSim.Presentation -{ - public abstract class concern_for_ExportProjectToSnapshotCommand : ContextSpecification - { - protected IProjectTask _projectTask; - - protected override void Context() - { - _projectTask= A.Fake(); - sut = new ExportProjectToSnapshotCommand(_projectTask); - } - } - - public class When_executing_the_export_project_to_snapshot_command : concern_for_ExportProjectToSnapshotCommand - { - protected override void Because() - { - sut.Execute(); - } - - [Observation] - public void should_leverage_the_snapshot_task_to_export_the_project_to_snapshot() - { - A.CallTo(() => _projectTask.ExportCurrentProjectToSnapshot()).MustHaveHappened(); - } - } -} \ No newline at end of file diff --git a/tests/PKSim.Tests/Presentation/LoadFromSnapshotPresenterSpecs.cs b/tests/PKSim.Tests/Presentation/LoadFromSnapshotPresenterSpecs.cs index bcb00a5b7..dfc714267 100644 --- a/tests/PKSim.Tests/Presentation/LoadFromSnapshotPresenterSpecs.cs +++ b/tests/PKSim.Tests/Presentation/LoadFromSnapshotPresenterSpecs.cs @@ -5,17 +5,15 @@ using OSPSuite.Assets; using OSPSuite.BDDHelper; using OSPSuite.BDDHelper.Extensions; -using OSPSuite.Core; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Services; +using OSPSuite.Presentation.DTO; using OSPSuite.Presentation.Presenters; +using OSPSuite.Presentation.Views; using OSPSuite.Utility.Events; -using PKSim.Assets; using PKSim.Core.Model; using PKSim.Core.Snapshots.Services; -using PKSim.Presentation.DTO.Snapshots; using PKSim.Presentation.Presenters.Snapshots; -using PKSim.Presentation.Views.Snapshots; namespace PKSim.Presentation { @@ -62,7 +60,7 @@ public void should_bind_to_the_view() [Observation] public void should_update_the_caption_based_on_the_snapshot_type() { - _view.Caption.ShouldBeEqualTo(PKSimConstants.UI.LoadObjectFromSnapshot(_objectType)); + _view.Caption.ShouldBeEqualTo(Captions.LoadObjectFromSnapshot(_objectType)); } } @@ -122,7 +120,7 @@ protected override void Context() var snapshotFile = "SnapshotFile"; A.CallTo(_dialogCreator).WithReturnType().Returns(snapshotFile); _loadFromSnapshotDTO.SnapshotFile = snapshotFile; - A.CallTo(() => _snapshotTask.LoadModelsFromSnapshotFileAsync(snapshotFile)).Returns(new[] {_individual}); + A.CallTo(() => _snapshotTask.LoadModelsFromSnapshotFileAsync(snapshotFile)).Returns(new[] { _individual }); A.CallTo(() => _view.Display()) .Invokes(x => sut.StartAsync().Wait()); sut.LoadModelFromSnapshot(); @@ -156,7 +154,7 @@ protected override void Context() var snapshotFile = "SnapshotFile"; A.CallTo(_dialogCreator).WithReturnType().Returns(snapshotFile); _loadFromSnapshotDTO.SnapshotFile = snapshotFile; - A.CallTo(() => _snapshotTask.LoadModelsFromSnapshotFileAsync(snapshotFile)).Returns(new[] {_individual}); + A.CallTo(() => _snapshotTask.LoadModelsFromSnapshotFileAsync(snapshotFile)).Returns(new[] { _individual }); A.CallTo(() => _view.Display()) .Invokes(x => sut.StartAsync().Wait()); } diff --git a/tests/PKSim.Tests/Presentation/LoadProjectFromSnapshotCommandSpecs.cs b/tests/PKSim.Tests/Presentation/LoadProjectFromSnapshotCommandSpecs.cs deleted file mode 100644 index f42560a61..000000000 --- a/tests/PKSim.Tests/Presentation/LoadProjectFromSnapshotCommandSpecs.cs +++ /dev/null @@ -1,32 +0,0 @@ -using FakeItEasy; -using OSPSuite.BDDHelper; -using PKSim.Presentation.Services; -using PKSim.Presentation.UICommands; - -namespace PKSim.Presentation -{ - public abstract class concern_for_LoadProjectFromSnapshotCommand : ContextSpecification - { - protected IProjectTask _projectTask; - - protected override void Context() - { - _projectTask = A.Fake(); - sut = new LoadProjectFromSnapshotUICommand(_projectTask); - } - } - - public class When_executing_the_load_project_from_snapshot_command : concern_for_LoadProjectFromSnapshotCommand - { - protected override void Because() - { - sut.Execute(); - } - - [Observation] - public void should_leverage_the_project_task_to_load_the_project_snapshot_in_the_current_project() - { - A.CallTo(() => _projectTask.LoadProjectFromSnapshot()).MustHaveHappened(); - } - } -} \ No newline at end of file diff --git a/tests/PKSim.Tests/Presentation/LoadProjectFromSnapshotPresenterSpecs.cs b/tests/PKSim.Tests/Presentation/LoadProjectFromSnapshotPresenterSpecs.cs index 7ae60a20b..6719ef161 100644 --- a/tests/PKSim.Tests/Presentation/LoadProjectFromSnapshotPresenterSpecs.cs +++ b/tests/PKSim.Tests/Presentation/LoadProjectFromSnapshotPresenterSpecs.cs @@ -1,17 +1,16 @@ using FakeItEasy; using OSPSuite.BDDHelper; using OSPSuite.BDDHelper.Extensions; -using OSPSuite.Core; using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.Services; using OSPSuite.Core.Services; using OSPSuite.Presentation.Presenters; +using OSPSuite.Presentation.Views; using OSPSuite.Utility.Events; using PKSim.Core.Model; using PKSim.Core.Services; using PKSim.Core.Snapshots.Services; using PKSim.Presentation.Presenters.Snapshots; -using PKSim.Presentation.Views.Snapshots; namespace PKSim.Presentation { @@ -25,7 +24,7 @@ public abstract class concern_for_LoadProjectFromSnapshotPresenter : ContextSpec protected IEventPublisher _eventPublisher; protected ILogPresenter _logPresenter; protected IRegistrationTask _registrationTask; - protected IQualiticationPlanRunner _qualificationPlanRunner; + protected IQualificationPlanRunner _qualificationPlanRunner; protected override void Context() { @@ -37,7 +36,7 @@ protected override void Context() _eventPublisher = A.Fake(); _logPresenter = A.Fake(); _registrationTask = A.Fake(); - _qualificationPlanRunner = A.Fake(); + _qualificationPlanRunner = A.Fake(); sut = new LoadProjectFromSnapshotPresenter( _view, diff --git a/tests/PKSim.Tests/Presentation/QualificationStepRunnerFactorySpecs.cs b/tests/PKSim.Tests/Presentation/QualificationStepRunnerFactorySpecs.cs index 164ed1685..4f1b80251 100644 --- a/tests/PKSim.Tests/Presentation/QualificationStepRunnerFactorySpecs.cs +++ b/tests/PKSim.Tests/Presentation/QualificationStepRunnerFactorySpecs.cs @@ -2,13 +2,15 @@ using FakeItEasy; using OSPSuite.BDDHelper; using OSPSuite.BDDHelper.Extensions; -using OSPSuite.Utility.Container; +using OSPSuite.Core.Domain; using PKSim.Core.Model; using PKSim.Core.Services; +using IContainer = OSPSuite.Utility.Container.IContainer; +using QualificationStepRunnerFactory = PKSim.Core.Services.QualificationStepRunnerFactory; namespace PKSim.Presentation { - public abstract class concern_for_QualificationStepRunnerFactory : ContextSpecification + public abstract class concern_for_QualificationStepRunnerFactory : ContextSpecification { private IContainer _container; protected RunParameterIdentificationQualificationStepRunner _runParameterIdentificationStepRunner; diff --git a/tests/PKSim.Tests/Presentation/QualiticationPlanRunnerSpecs.cs b/tests/PKSim.Tests/Presentation/QualiticationPlanRunnerSpecs.cs deleted file mode 100644 index 277b19660..000000000 --- a/tests/PKSim.Tests/Presentation/QualiticationPlanRunnerSpecs.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Threading.Tasks; -using FakeItEasy; -using Microsoft.Extensions.Logging; -using OSPSuite.BDDHelper; -using OSPSuite.Core.Domain; -using PKSim.Assets; -using PKSim.Core.Model; -using PKSim.Core.Services; -using OSPSuite.Core.Services; - - -namespace PKSim.Presentation -{ - public abstract class concern_for_QualiticationPlanRunner : ContextSpecificationAsync - { - protected IQualificationStepRunnerFactory _qualificationStepRunnerFactory; - protected IOSPSuiteLogger _logger; - - protected override Task Context() - { - _qualificationStepRunnerFactory = A.Fake(); - _logger = A.Fake(); - sut = new QualiticationPlanRunner(_qualificationStepRunnerFactory, _logger); - - return _completed; - } - } - - public class When_running_a_qualification_plan : concern_for_QualiticationPlanRunner - { - private QualificationPlan _qualificationPlan; - private IQualificationStep _step1; - private IQualificationStep _step2; - private IQualificationStepRunner _qualificationStepRunner1; - private IQualificationStepRunner _qualificationStepRunner2; - - protected override async Task Context() - { - await base.Context(); - _step1 = A.Fake(); - _step2 = A.Fake(); - _qualificationPlan = new QualificationPlan {_step1, _step2}.WithName("QP"); - - _qualificationStepRunner1 = A.Fake(); - _qualificationStepRunner2 = A.Fake(); - - A.CallTo(() => _qualificationStepRunnerFactory.CreateFor(_step1)).Returns(_qualificationStepRunner1); - A.CallTo(() => _qualificationStepRunnerFactory.CreateFor(_step2)).Returns(_qualificationStepRunner2); - } - - protected override Task Because() - { - return sut.RunAsync(_qualificationPlan); - } - - [Observation] - public void should_log_debug_the_fact_that_the_qualification_run_is_starting() - { - A.CallTo(() => _logger.AddToLog(PKSimConstants.Information.StartingQualificationPlan(_qualificationPlan.Name), LogLevel.Debug, A._)).MustHaveHappened(); - } - - [Observation] - public void should_iterate_through_all_qualification_steps_in_order_and_execute_them() - { - A.CallTo(() => _qualificationStepRunner1.RunAsync(_step1)).MustHaveHappened() - .Then(A.CallTo(() => _qualificationStepRunner2.RunAsync(_step2)).MustHaveHappened()); - } - - [Observation] - public void should_have_disposed_of_all_qualification_step_runners_created_during_the_run() - { - A.CallTo(() => _qualificationStepRunner1.Dispose()).MustHaveHappened(); - A.CallTo(() => _qualificationStepRunner2.Dispose()).MustHaveHappened(); - } - } -} \ No newline at end of file diff --git a/tests/PKSim.Tests/Presentation/RunParameterIdentificationQualificationStepRunnerSpecs.cs b/tests/PKSim.Tests/Presentation/RunParameterIdentificationQualificationStepRunnerSpecs.cs index a2e8e4106..a54723235 100644 --- a/tests/PKSim.Tests/Presentation/RunParameterIdentificationQualificationStepRunnerSpecs.cs +++ b/tests/PKSim.Tests/Presentation/RunParameterIdentificationQualificationStepRunnerSpecs.cs @@ -1,7 +1,9 @@ using System.Threading.Tasks; using FakeItEasy; using Microsoft.Extensions.Logging; +using OSPSuite.Assets; using OSPSuite.BDDHelper; +using OSPSuite.Core.Domain; using OSPSuite.Core.Domain.ParameterIdentifications; using OSPSuite.Core.Domain.Services.ParameterIdentifications; using PKSim.Assets; @@ -50,7 +52,7 @@ protected override Task Because() [Observation] public void should_have_debug_logged_the_fact_that_the_qualification_step_was_starting() { - A.CallTo(() => _logger.AddToLog(PKSimConstants.Information.StartingQualificationStep(_runParameterIdentificationStep.Display), LogLevel.Debug, A._)).MustHaveHappened(); + A.CallTo(() => _logger.AddToLog(Captions.StartingQualificationStep(_runParameterIdentificationStep.Display), LogLevel.Debug, A._)).MustHaveHappened(); } [Observation] diff --git a/tests/PKSim.Tests/Presentation/RunSimulationQualificationStepRunnerSpecs.cs b/tests/PKSim.Tests/Presentation/RunSimulationQualificationStepRunnerSpecs.cs index e62b34cda..8c687fa8d 100644 --- a/tests/PKSim.Tests/Presentation/RunSimulationQualificationStepRunnerSpecs.cs +++ b/tests/PKSim.Tests/Presentation/RunSimulationQualificationStepRunnerSpecs.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using FakeItEasy; using OSPSuite.BDDHelper; -using OSPSuite.BDDHelper.Extensions; using OSPSuite.Core.Services; using PKSim.Core.Model; using PKSim.Core.Services; diff --git a/tests/PKSim.UI.Tests/PKSim.UI.Tests.csproj b/tests/PKSim.UI.Tests/PKSim.UI.Tests.csproj index afc61acc7..b0298e439 100644 --- a/tests/PKSim.UI.Tests/PKSim.UI.Tests.csproj +++ b/tests/PKSim.UI.Tests/PKSim.UI.Tests.csproj @@ -24,11 +24,11 @@ - + - + - +