Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #2643 when to show global pk analysis #2644

Merged
merged 3 commits into from
May 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 64 additions & 37 deletions src/PKSim.Core/Services/PKAnalysesTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,19 @@ public interface IPKAnalysesTask : OSPSuite.Core.Domain.Services.IPKAnalysesTask
/// Starts the calculation of the Auc DDI Ratio for all compounds /> by switching off all other applications
/// </summary>
void CalculateDDIRatioFor(Simulation simulation);

/// <summary>
/// Returns true if global pk-analysis can be calculated for the given <paramref name="protocol" /> otherwise false
/// </summary>
/// <param name="protocol"></param>
/// <returns></returns>
bool CanCalculateGlobalPKFor(Protocol protocol);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems to be the right place, where we calculate global pk, to wonder if we can calculate global pk. Doing this in the presenter was not cohesive.


/// <summary>
/// Returns true if global pk-analysis can be calculated for the given <paramref name="simulation" /> otherwise false
/// </summary>
/// <param name="simulation"></param>
bool CanCalculateGlobalPKFor(Simulation simulation);
}

public class PKAnalysesTask : OSPSuite.Core.Domain.Services.PKAnalysesTask, IPKAnalysesTask
Expand All @@ -92,7 +105,7 @@ public class PKAnalysesTask : OSPSuite.Core.Domain.Services.PKAnalysesTask, IPKA
private readonly IStatisticalDataCalculator _statisticalDataCalculator;
private readonly IRepresentationInfoRepository _representationInfoRepository;
private readonly IParameterFactory _parameterFactory;
private readonly IProtocolToSchemaItemsMapper _protocolToSchemaItemsMapper;
private readonly IProtocolToSchemaItemsMapper _protocolMapper;
private readonly IProtocolFactory _protocolFactory;
private readonly IGlobalPKAnalysisRunner _globalPKAnalysisRunner;
private readonly IVSSCalculator _vssCalculator;
Expand All @@ -108,7 +121,7 @@ public PKAnalysesTask(ILazyLoadTask lazyLoadTask,
IDimensionRepository dimensionRepository,
IStatisticalDataCalculator statisticalDataCalculator,
IRepresentationInfoRepository representationInfoRepository,
IParameterFactory parameterFactory, IProtocolToSchemaItemsMapper protocolToSchemaItemsMapper, IProtocolFactory protocolFactory,
IParameterFactory parameterFactory, IProtocolToSchemaItemsMapper protocolMapper, IProtocolFactory protocolFactory,
IGlobalPKAnalysisRunner globalPKAnalysisRunner, IVSSCalculator vssCalculator, IInteractionTask interactionTask, ICloner cloner, IEntityPathResolver entityPathResolver) :
base(lazyLoadTask, pkValuesCalculator, pkParameterRepository, pkCalculationOptionsFactory)
{
Expand All @@ -121,7 +134,7 @@ public PKAnalysesTask(ILazyLoadTask lazyLoadTask,
_statisticalDataCalculator = statisticalDataCalculator;
_representationInfoRepository = representationInfoRepository;
_parameterFactory = parameterFactory;
_protocolToSchemaItemsMapper = protocolToSchemaItemsMapper;
_protocolMapper = protocolMapper;
_protocolFactory = protocolFactory;
_globalPKAnalysisRunner = globalPKAnalysisRunner;
_vssCalculator = vssCalculator;
Expand Down Expand Up @@ -356,13 +369,13 @@ private IContainer calculateGlobalPKAnalysisFor(Simulation simulation, string co
vssPlasma.Value *= bioAvailabilityValue;
vdPlasma.Value *= bioAvailabilityValue;
totalPlasmaCL.Value *= bioAvailabilityValue;
fractionAbsorbedWarningParameters.AddRange(new[] { vssPlasma, vdPlasma });
pkValues.AddRange(new[] { vssPlasma, vdPlasma, totalPlasmaCL, bioAvailability });
fractionAbsorbedWarningParameters.AddRange(new[] {vssPlasma, vdPlasma});
pkValues.AddRange(new[] {vssPlasma, vdPlasma, totalPlasmaCL, bioAvailability});
}
else
{
fractionAbsorbedWarningParameters.AddRange(new[] { vssPlasmaOverF, vdPlasmaOverF });
pkValues.AddRange(new[] { vssPlasmaOverF, vdPlasmaOverF, totalPlasmaCLOverF, bioAvailability });
fractionAbsorbedWarningParameters.AddRange(new[] {vssPlasmaOverF, vdPlasmaOverF});
pkValues.AddRange(new[] {vssPlasmaOverF, vdPlasmaOverF, totalPlasmaCLOverF, bioAvailability});
}


Expand Down Expand Up @@ -396,13 +409,7 @@ private static IEnumerable<QuantityPKParameter> mapQuantityPKParametersFromIndiv
// use the first in series as a template to retrieve from all individual results.
// The list of parameters should be identical for all the individual global analyses.
var aPKAnalysis = globalIndividualPKParameterCache.FirstOrDefault();
aPKAnalysis?.AllPKParameters.GroupBy(moleculeNameFrom).Each(group =>
{
group.Each(pKParameter =>
{
quantityPKList.Add(quantityPKParameterFor(globalIndividualPKParameterCache, pKParameter, group.Key));
});
});
aPKAnalysis?.AllPKParameters.GroupBy(moleculeNameFrom).Each(group => { group.Each(pKParameter => { quantityPKList.Add(quantityPKParameterFor(globalIndividualPKParameterCache, pKParameter, group.Key)); }); });

return quantityPKList;
}
Expand All @@ -420,9 +427,9 @@ private static QuantityPKParameter quantityPKParameterFor(ICache<int, GlobalPKAn
if (firstParameter == null)
return new QuantityPKParameter();

var quantityPKParameter = new QuantityPKParameter { Dimension = firstParameter.Dimension, Name = firstParameter.Name, QuantityPath = quantityPath };
var quantityPKParameter = new QuantityPKParameter {Dimension = firstParameter.Dimension, Name = firstParameter.Name, QuantityPath = quantityPath};

pKValuesForPKParameter.Each(pKValue => { quantityPKParameter.SetValue(pKValuesForPKParameter.IndexOf(pKValue), (float)pKValue.Value); });
pKValuesForPKParameter.Each(pKValue => { quantityPKParameter.SetValue(pKValuesForPKParameter.IndexOf(pKValue), (float) pKValue.Value); });
return quantityPKParameter;
}

Expand Down Expand Up @@ -528,7 +535,7 @@ public void CalculateBioavailabilityFor(Simulation simulation, string compoundNa
// We know this is a valid cast because it is cloned from simulation
var populationSimulation = simulation.DowncastTo<PopulationSimulation>();
CalculateFor(ivPopulationSimulation, ivCompoundPKContext);
var contextForPopulationSimulation = createContextForPopulationSimulation(ivCompoundPKContext, mapFromBioavailabilityCompoundPK, compoundName, populationSimulation, new[] { Bioavailability });
var contextForPopulationSimulation = createContextForPopulationSimulation(ivCompoundPKContext, mapFromBioavailabilityCompoundPK, compoundName, populationSimulation, new[] {Bioavailability});
populationSimulation.PKAnalyses = CalculateFor(populationSimulation, contextForPopulationSimulation);
}
else if (ivSimulation is IndividualSimulation ivIndividualSimulation)
Expand Down Expand Up @@ -574,7 +581,7 @@ public void CalculateDDIRatioFor(Simulation simulation)

// First calculate the compound context. We will know the AucInf and CMax when DDI is turned off
CalculateFor(ddiPopulationSimulation, ddiCompoundPKContext);
var parameterNames = new[] { AUCRatio, C_maxRatio };
var parameterNames = new[] {AUCRatio, C_maxRatio};

// From the ddi context, create the context from the original simulation and the ddi simulation for calculating ddi ratio parameters
var contextForPopulationSimulation = createContextForPopulationSimulation(ddiCompoundPKContext, mapFromDDISimulationCompoundPK, compoundName, populationSimulation, parameterNames);
Expand All @@ -592,6 +599,28 @@ public void CalculateDDIRatioFor(Simulation simulation)
simulation.HasChanged = true;
}

public bool CanCalculateGlobalPKFor(Protocol protocol)
{
var schemaItems = _protocolMapper.MapFrom(protocol);
if (schemaItems == null || schemaItems.Count == 0)
return false;

//only one item, supported for IV or ORAL
var schemaItem = schemaItems[0];
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Yuri05 As discussed in the issue

if (schemaItems.Count == 1)
return isOral(schemaItem) || isIntravenous(schemaItem);

//two items. Only ok if all are ORAL
return schemaItems.All(isOral);
}

public bool CanCalculateGlobalPKFor(Simulation simulation)
{
return simulation.Compounds.Select(compound => protocolFor(simulation, compound))
.Where(p => p != null)
.Any(CanCalculateGlobalPKFor);
}

private CompoundPKContext createContextForPopulationSimulation(CompoundPKContext contextCompoundPK, Func<CompoundPK, CompoundPK> compoundPKMapper, string compoundName, PopulationSimulation populationSimulation, string[] parameterNames)
{
var contextForPopulationSimulation = new CompoundPKContext();
Expand All @@ -603,14 +632,14 @@ private CompoundPKContext createContextForPopulationSimulation(CompoundPKContext

private CompoundPK mapFromBioavailabilityCompoundPK(CompoundPK bioAvailabilitySimulationCompoundPK)
{
var compoundPK = new CompoundPK { CompoundName = bioAvailabilitySimulationCompoundPK.CompoundName };
var compoundPK = new CompoundPK {CompoundName = bioAvailabilitySimulationCompoundPK.CompoundName};
bioAvailabilitySimulationCompoundPK.AllBioAvailabilityAucInf.KeyValues.Each(bioAvailability => { compoundPK.AddBioavailability(bioAvailability.Key, bioAvailability.Value); });
return compoundPK;
}

private CompoundPK mapFromDDISimulationCompoundPK(CompoundPK ddiSimulationCompoundPK)
{
var compoundPK = new CompoundPK { CompoundName = ddiSimulationCompoundPK.CompoundName };
var compoundPK = new CompoundPK {CompoundName = ddiSimulationCompoundPK.CompoundName};
ddiSimulationCompoundPK.AllDDIAucInf.KeyValues.Each(aucInf => compoundPK.AddDDIAucInf(aucInf.Key, aucInf.Value));
ddiSimulationCompoundPK.AllDDICMax.KeyValues.Each(cMax => compoundPK.AddDDICMax(cMax.Key, cMax.Value));
return compoundPK;
Expand Down Expand Up @@ -676,13 +705,11 @@ private SchemaItem singleDosingItem(Simulation simulation, Compound compound)
return schemaItemsFrom(simulation, compound).FirstOrDefault();
}

private Protocol protocolFor(Simulation simulation, Compound compound) => simulation.CompoundPropertiesFor(compound).ProtocolProperties.Protocol;

private IReadOnlyList<SchemaItem> schemaItemsFrom(Simulation simulation, Compound compound)
{
var protocol = simulation.CompoundPropertiesFor(compound).ProtocolProperties.Protocol;
if (protocol == null)
return new List<SchemaItem>();

return _protocolToSchemaItemsMapper.MapFrom(protocol);
return _protocolMapper.MapFrom(protocolFor(simulation, compound));
}

private enum ApplicationType
Expand All @@ -705,7 +732,7 @@ public IEnumerable<PopulationPKAnalysis> CalculateFor(IPopulationDataCollector p
return pkAnalyses; // there are no analyses to calculate

var allColumns = timeProfileChartData.Panes.SelectMany(x => x.Curves).SelectMany(x =>
columnsFor(x, populationDataCollector).Select(column => new { curveData = x, column }))
columnsFor(x, populationDataCollector).Select(column => new {curveData = x, column}))
.Where(c => c.column.IsConcentration());

var columnsByMolecules = allColumns.GroupBy(x => x.column.MoleculeName());
Expand Down Expand Up @@ -748,7 +775,7 @@ public IEnumerable<IndividualPKAnalysis> CalculateFor(IReadOnlyList<Simulation>

private IEnumerable<DataColumn> columnsFor(CurveData<TimeProfileXValue, TimeProfileYValue> curveData, IPopulationDataCollector populationDataCollector)
{
var baseGrid = new BaseGrid(Constants.TIME, curveData.XAxis.Dimension) { Values = curveData.XValues.Select(x => x.X).ToList() };
var baseGrid = new BaseGrid(Constants.TIME, curveData.XAxis.Dimension) {Values = curveData.XValues.Select(x => x.X).ToList()};

if (curveData.IsRange())
{
Expand All @@ -758,14 +785,14 @@ private IEnumerable<DataColumn> columnsFor(CurveData<TimeProfileXValue, TimeProf
new DataColumn(lowerRange, curveData.YAxis.Dimension, baseGrid)
{
Values = curveData.YValues.Select(y => y.LowerValue).ToList(),
DataInfo = { MolWeight = populationDataCollector.MolWeightFor(curveData.QuantityPath) },
QuantityInfo = { Path = curveData.QuantityPath.ToPathArray() }
DataInfo = {MolWeight = populationDataCollector.MolWeightFor(curveData.QuantityPath)},
QuantityInfo = {Path = curveData.QuantityPath.ToPathArray()}
},
new DataColumn(upperRange, curveData.YAxis.Dimension, baseGrid)
{
Values = curveData.YValues.Select(y => y.UpperValue).ToList(),
DataInfo = { MolWeight = populationDataCollector.MolWeightFor(curveData.QuantityPath) },
QuantityInfo = { Path = curveData.QuantityPath.ToPathArray() }
DataInfo = {MolWeight = populationDataCollector.MolWeightFor(curveData.QuantityPath)},
QuantityInfo = {Path = curveData.QuantityPath.ToPathArray()}
}
};
}
Expand All @@ -775,8 +802,8 @@ private IEnumerable<DataColumn> columnsFor(CurveData<TimeProfileXValue, TimeProf
new DataColumn(curveData.Caption, curveData.YAxis.Dimension, baseGrid)
{
Values = curveData.YValues.Select(y => y.Y).ToList(),
DataInfo = { MolWeight = populationDataCollector.MolWeightFor(curveData.QuantityPath) },
QuantityInfo = { Path = curveData.QuantityPath.ToPathArray() }
DataInfo = {MolWeight = populationDataCollector.MolWeightFor(curveData.QuantityPath)},
QuantityInfo = {Path = curveData.QuantityPath.ToPathArray()}
}
};
}
Expand All @@ -786,7 +813,7 @@ public IndividualPKAnalysis CalculateFor(Simulation simulation, DataColumn dataC
if (dataColumn == null)
return new NullIndividualPKAnalysis();

return CalculateFor(new[] { simulation }, new[] { dataColumn }).FirstOrDefault() ?? new NullIndividualPKAnalysis();
return CalculateFor(new[] {simulation}, new[] {dataColumn}).FirstOrDefault() ?? new NullIndividualPKAnalysis();
}

private PKValues calculatePK(DataColumn column, PKCalculationOptions options)
Expand Down Expand Up @@ -863,13 +890,13 @@ public PKAnalysis CreatePKAnalysisFromValues(PKValues pkValues, Simulation simul
/// </returns>
private (string lowerRange, string upperRange) rangeDescriptions(string text)
{
var splitStrings = text.Split(new[] { "Range" }, StringSplitOptions.None);
var splitStrings = text.Split(new[] {"Range"}, StringSplitOptions.None);
var match = splitStrings.Length == 2;

if (!match)
return (text, text);

var upperAndLowerRange = splitStrings.Last().Split(new[] { "to" }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();
var upperAndLowerRange = splitStrings.Last().Split(new[] {"to"}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();

return ($"{splitStrings[0]}{upperAndLowerRange[0]}", $"{splitStrings[0]}{upperAndLowerRange[1]}");
}
Expand Down Expand Up @@ -918,7 +945,7 @@ private string correctNameFromMetric(string originalText, bool multipleValues, b
suffix = isLowerValue ? lowerRange : upperRange;
}

return (new[] { captionPrefix, suffix }).ToCaption();
return (new[] {captionPrefix, suffix}).ToCaption();
}

private CurveData<TimeProfileXValue, TimeProfileYValue> buildCurveData(QuantityPKParameter quantityPKParameter, string caption)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
using OSPSuite.Utility.Extensions;
using PKSim.Assets;
using PKSim.Core;
using PKSim.Core.Mappers;
using PKSim.Core.Model;
using PKSim.Core.Repositories;
using PKSim.Core.Services;
Expand Down Expand Up @@ -45,23 +44,20 @@ public class GlobalPKAnalysisPresenter : AbstractSubPresenter<IGlobalPKAnalysisV
private GlobalPKAnalysisDTO _globalPKAnalysisDTO;
private DefaultPresentationSettings _settings;
private readonly IPresentationSettingsTask _presentationSettingsTask;
private readonly IProtocolToSchemaItemsMapper _protocolToSchemaItemsMapper;

public GlobalPKAnalysisPresenter(
IGlobalPKAnalysisView view,
IPKAnalysesTask pkAnalysesTask,
IGlobalPKAnalysisToGlobalPKAnalysisDTOMapper globalPKAnalysisDTOMapper,
IHeavyWorkManager heavyWorkManager,
IRepresentationInfoRepository representationInfoRepository,
IPresentationSettingsTask presentationSettingsTask,
IProtocolToSchemaItemsMapper protocolToSchemaItemsMapper) : base(view)
IPresentationSettingsTask presentationSettingsTask) : base(view)
{
_pkAnalysesTask = pkAnalysesTask;
_globalPKAnalysisDTOMapper = globalPKAnalysisDTOMapper;
_heavyWorkManager = heavyWorkManager;
_representationInfoRepository = representationInfoRepository;
_presentationSettingsTask = presentationSettingsTask;
_protocolToSchemaItemsMapper = protocolToSchemaItemsMapper;
_settings = new DefaultPresentationSettings();
}

Expand Down Expand Up @@ -124,6 +120,7 @@ private void loadPreferredUnitsForPKAnalysis()
{
if (_settings == null)
return;

GlobalPKAnalysis.AllPKParameterNames.Each(updateParameterDisplayUnits);
}

Expand All @@ -141,20 +138,11 @@ public void ChangeUnit(string parameterName, Unit newUnit)
updateView();
}

public Unit DisplayUnitFor(string parameterName)
{
return pkParameterNamed(parameterName).DisplayUnit;
}
public Unit DisplayUnitFor(string parameterName) => pkParameterNamed(parameterName).DisplayUnit;

public IEnumerable<Unit> AvailableUnitsFor(string parameterName)
{
return pkParameterNamed(parameterName).Dimension.Units;
}
public IEnumerable<Unit> AvailableUnitsFor(string parameterName) => pkParameterNamed(parameterName).Dimension.Units;

private IParameter pkParameterNamed(string parameterName)
{
return GlobalPKAnalysis.PKParameters(parameterName).First();
}
private IParameter pkParameterNamed(string parameterName) => GlobalPKAnalysis.PKParameters(parameterName).First();

public string DisplayNameFor(string parameterName)
{
Expand All @@ -173,14 +161,9 @@ public bool HasParameters()

public bool CanCalculateGlobalPK()
{
return firstSimulation.Compounds.Select(compound => firstSimulation.CompoundPropertiesFor(compound).ProtocolProperties.Protocol)
.Where(p => p != null)
.Select(_protocolToSchemaItemsMapper.MapFrom)
.Any(x => !isMultipleIV(x));
return _simulations.Count == 1 && _pkAnalysesTask.CanCalculateGlobalPKFor(firstSimulation);
}

private bool isMultipleIV(IReadOnlyList<SchemaItem> schemaItems) => schemaItems.Count(x => x.IsIV) > 1;

public void LoadSettingsForSubject(IWithId subject)
{
_settings = _presentationSettingsTask.PresentationSettingsFor<DefaultPresentationSettings>(this, subject);
Expand Down
Loading