def addSample(self, sampleName): newSampleAdissol = PKPDSample() newSampleAdissol.sampleName = sampleName newSampleAdissol.variableDictPtr = self.outputExperiment.variables newSampleAdissol.descriptors = {} newSampleAdissol.addMeasurementColumn("tvitro", self.tvitroUnique) newSampleAdissol.addMeasurementColumn("Adissol", self.AdissolUnique) self.outputExperiment.samples[sampleName] = newSampleAdissol
def addSample(self, sampleName, t, y): newSample = PKPDSample() newSample.sampleName = sampleName newSample.variableDictPtr = self.outputExperiment.variables newSample.descriptors = {} newSample.addMeasurementPattern(["A"]) newSample.addMeasurementColumn("t", t) newSample.addMeasurementColumn("A", y) self.outputExperiment.samples[sampleName] = newSample
def addSample(self, outputExperiment, sampleName, tvitro, tvivo, individualFrom, vesselFrom): newSample = PKPDSample() newSample.sampleName = sampleName newSample.variableDictPtr = self.outputExperiment.variables newSample.descriptors = {} newSample.addMeasurementColumn("tvivo", tvivo) newSample.addMeasurementColumn("tvitro", tvitro) outputExperiment.samples[sampleName] = newSample outputExperiment.addLabelToSample( sampleName, "from", "individual---vesel", "%s---%s" % (individualFrom, vesselFrom))
def calculateAllLevy(self): L1 = [] for ptrExperiment in self.inputLevyplots: experiment = PKPDExperiment() experiment.load(ptrExperiment.get().fnPKPD.get()) x, y = experiment.getXYMeanValues("tvivo", "tvitro") L1.append((x, y)) tvivo, tvitro = computeXYmean(L1, common=True) x, y = twoWayUniqueFloatValues(tvivo, tvitro) Bt = InterpolatedUnivariateSpline(x, y, k=1) vtvitroReinterpolated = np.zeros(len(tvivo)) for i in range(len(tvivo)): tvivoi = tvivo[i] vtvitroReinterpolated[i] = Bt(tvivoi) tvitroReinterpolatedVar = experiment.variables["tvitro"] tvivoVar = experiment.variables["tvivo"] self.outputExperimentSingle = PKPDExperiment() self.outputExperimentSingle.variables[ tvitroReinterpolatedVar.varName] = tvitroReinterpolatedVar self.outputExperimentSingle.variables[tvivoVar.varName] = tvivoVar self.outputExperimentSingle.general["title"] = "Levy plot" self.outputExperimentSingle.general["comment"] = "tvitro vs tvivo" sampleName = "jointLevyPlot" newSampleSingle = PKPDSample() newSampleSingle.sampleName = sampleName newSampleSingle.variableDictPtr = self.outputExperimentSingle.variables newSampleSingle.descriptors = {} newSampleSingle.addMeasurementColumn("tvitro", vtvitroReinterpolated) newSampleSingle.addMeasurementColumn("tvivo", tvivo) self.outputExperimentSingle.samples[sampleName] = newSampleSingle self.outputExperimentSingle.addLabelToSample(sampleName, "from", "individual---vesel", "meanVivo---meanVitro") self.outputExperimentSingle.write(self._getPath("experiment.pkpd"))
def createOutputStep(self, objId): fnFile = os.path.basename(self.inputFile.get()) copyFile(self.inputFile.get(), self._getPath(fnFile)) tables = self.readTables(self._getPath(fnFile)) for tableName, sampleNames, allT, allMeasurements in tables: self.experiment = PKPDExperiment() self.experiment.general["title"] = self.title.get() self.experiment.general["comment"] = self.comment.get() # Add variables if not self.addVar(self.experiment, self.tVar.get()): raise Exception("Cannot process time variable") if not self.addVar(self.experiment, self.xVar.get()): raise Exception("Cannot process measurement variable") tvarName = self.tVar.get().split(';')[0].replace(';', '') xvarName = self.xVar.get().split(';')[0].replace(';', '') # Create the samples for sampleName in sampleNames: self.experiment.samples[sampleName] = PKPDSample() self.experiment.samples[sampleName].parseTokens( [sampleName], self.experiment.variables, self.experiment.doses, self.experiment.groups) self.experiment.samples[sampleName].addMeasurementPattern( [sampleName, tvarName, xvarName]) samplePtr = self.experiment.samples[sampleName] exec("samplePtr.measurement_%s=%s" % (tvarName, allT)) # Fill the samples for i in range(len(allT)): for j in range(len(sampleNames)): samplePtr = self.experiment.samples[sampleNames[j]] exec('samplePtr.measurement_%s.append("%s")' % (xvarName, allMeasurements[i][j])) self.experiment.write( self._getPath("experiment%s.pkpd" % tableName)) self.experiment._printToStream(sys.stdout) self._defineOutputs( **{"outputExperiment%s" % tableName: self.experiment})
def runDrop(self, objId, varsToDrop): import copy experiment = self.readExperiment(self.inputExperiment.get().fnPKPD) self.printSection("Dropping variables") varsToDrop = [] for varName in self.varsToDrop.get().split(','): varsToDrop.append(varName.strip()) filteredExperiment = PKPDExperiment() filteredExperiment.general = copy.copy(experiment.general) filteredExperiment.variables = {} for varName, variable in experiment.variables.items(): if not varName in varsToDrop: filteredExperiment.variables[varName] = copy.copy(variable) filteredExperiment.samples = {} filteredExperiment.doses = copy.copy(experiment.doses) for sampleKey, sample in experiment.samples.items(): candidateSample = PKPDSample() candidateSample.variableDictPtr = filteredExperiment.variables candidateSample.doseDictPtr = filteredExperiment.doses candidateSample.sampleName = copy.copy(sample.sampleName) candidateSample.doseList = copy.copy(sample.doseList) candidateSample.descriptors = copy.copy(sample.descriptors) candidateSample.measurementPattern = [] for varName in sample.measurementPattern: if not varName in varsToDrop: candidateSample.measurementPattern.append(varName) exec( "candidateSample.measurement_%s = copy.copy(sample.measurement_%s)" % (varName, varName)) filteredExperiment.samples[ candidateSample.varName] = candidateSample self.writeExperiment(filteredExperiment, self._getPath("experiment.pkpd")) self.experiment = filteredExperiment
def calculateAllIvIvC(self): L1 = [] L2 = [] L3 = [] L4 = [] L5 = [] for ptrExperiment in self.inputIVIVCs: experiment = PKPDExperiment() experiment.load(ptrExperiment.get().fnPKPD.get()) x, y = experiment.getXYMeanValues("tvivo", "tvitroReinterpolated") L1.append((x, y)) x, y = experiment.getXYMeanValues("tvivo", "Fabs") L2.append((x, y)) x, y = experiment.getXYMeanValues("AdissolReinterpolated", "FabsPredicted") L3.append((x, y)) x, y = experiment.getXYMeanValues("FabsPredicted", "Fabs") L4.append((x, y)) x, y = experiment.getXYMeanValues("tvitroReinterpolated", "AdissolReinterpolated") L5.append((x, y)) tvivo1, tvitroReinterpolatedY = computeXYmean(L1, common=True) tvivoOrig, FabsOrig = computeXYmean(L2, common=True) AdissolReinterpolatedX, FabsPredictedY = computeXYmean(L3, common=True) FabsPredictedX, Fabs = computeXYmean(L4, common=True) tvitroReinterpolatedX, AdissolReinterpolatedY = computeXYmean( L5, common=True) x, y = twoWayUniqueFloatValues(tvivo1, tvitroReinterpolatedY) Bt = InterpolatedUnivariateSpline(x, y, k=1) x, y = twoWayUniqueFloatValues(tvitroReinterpolatedX, AdissolReinterpolatedY) BtA = InterpolatedUnivariateSpline(x, y, k=1) x, y = twoWayUniqueFloatValues(tvivoOrig, FabsOrig) BtF = InterpolatedUnivariateSpline(x, y, k=1) x, y = twoWayUniqueFloatValues(AdissolReinterpolatedX, FabsPredictedY) BAF = InterpolatedUnivariateSpline(x, y, k=1) x, y = twoWayUniqueFloatValues(FabsPredictedX, Fabs) BFF = InterpolatedUnivariateSpline(x, y, k=1) vtvitroReinterpolated = np.zeros(len(tvivo1)) vAdissolReinterpolated = np.zeros(len(tvivo1)) vFabs = np.zeros(len(tvivo1)) vFabsPredicted = np.zeros(len(tvivo1)) vFabsOrig = np.zeros(len(tvivo1)) for i in range(len(tvivo1)): tvivoi = tvivo1[i] vtvitroReinterpolated[i] = Bt(tvivoi) vAdissolReinterpolated[i] = BtA(vtvitroReinterpolated[i]) vFabsPredicted[i] = BAF(vAdissolReinterpolated[i]) vFabs[i] = BFF(vFabsPredicted[i]) vFabsOrig[i] = BtF(tvivoi) tvitroReinterpolatedVar = experiment.variables["tvitroReinterpolated"] AdissolReinterpolatedVar = experiment.variables[ "AdissolReinterpolated"] tvivoVar = experiment.variables["tvivo"] FabsOrigVar = copy.copy(experiment.variables["Fabs"]) FabsOrigVar.varName = "FabsOriginal" FabsVar = experiment.variables["Fabs"] FabsVar.comment += ". After IVIVC: tvivo->tvitro->Adissol->Fabs " FabsPredictedVar = experiment.variables["FabsPredicted"] self.outputExperimentFabsSingle = PKPDExperiment() self.outputExperimentFabsSingle.variables[ tvitroReinterpolatedVar.varName] = tvitroReinterpolatedVar self.outputExperimentFabsSingle.variables[ AdissolReinterpolatedVar.varName] = AdissolReinterpolatedVar self.outputExperimentFabsSingle.variables[tvivoVar.varName] = tvivoVar self.outputExperimentFabsSingle.variables[FabsVar.varName] = FabsVar self.outputExperimentFabsSingle.variables[ FabsPredictedVar.varName] = FabsPredictedVar self.outputExperimentFabsSingle.variables[ FabsOrigVar.varName] = FabsOrigVar self.outputExperimentFabsSingle.general[ "title"] = "In-vitro In-vivo correlation" self.outputExperimentFabsSingle.general[ "comment"] = "Fabs vs Predicted Fabs" sampleName = "jointIVIVC" newSampleFabsSingle = PKPDSample() newSampleFabsSingle.sampleName = sampleName newSampleFabsSingle.variableDictPtr = self.outputExperimentFabsSingle.variables newSampleFabsSingle.descriptors = {} newSampleFabsSingle.addMeasurementColumn("tvitroReinterpolated", vtvitroReinterpolated) newSampleFabsSingle.addMeasurementColumn("AdissolReinterpolated", vAdissolReinterpolated) newSampleFabsSingle.addMeasurementColumn("tvivo", tvivo1) newSampleFabsSingle.addMeasurementColumn("FabsPredicted", vFabsPredicted) newSampleFabsSingle.addMeasurementColumn("Fabs", vFabs) newSampleFabsSingle.addMeasurementColumn("FabsOriginal", vFabsOrig) self.outputExperimentFabsSingle.samples[ sampleName] = newSampleFabsSingle self.outputExperimentFabsSingle.addLabelToSample( sampleName, "from", "individual---vesel", "AvgVivo---AvgVitro") self.outputExperimentFabsSingle.write( self._getPath("experimentFabsSingle.pkpd"))
def runSimulate(self, Nsimulations, confidenceInterval, doses): if self.odeSource.get() == self.SRC_ODE: self.protODE = self.inputODE.get() if hasattr(self.protODE, "outputExperiment"): self.experiment = self.readExperiment( self.protODE.outputExperiment.fnPKPD) elif hasattr(self.protODE, "outputExperiment1"): self.experiment = self.readExperiment( self.protODE.outputExperiment1.fnPKPD) else: raise Exception( "Cannot find an outputExperiment in the input ODE") if self.paramsSource.get() == ProtPKPDODESimulate.PRM_POPULATION: self.fitting = self.readFitting( self.inputPopulation.get().fnFitting, cls="PKPDSampleFitBootstrap") elif self.paramsSource.get() == ProtPKPDODESimulate.PRM_FITTING: self.fitting = self.readFitting( self.inputFitting.get().fnFitting) else: # User defined or experiment if hasattr(self.protODE, "outputFitting"): self.fitting = self.readFitting( self.protODE.outputFitting.fnFitting) elif hasattr(self.protODE, "outputFitting1"): self.fitting = self.readFitting( self.protODE.outputFitting1.fnFitting) self.varNameX = self.fitting.predictor.varName if type(self.fitting.predicted) != list: self.varNameY = self.fitting.predicted.varName else: self.varNameY = [var.varName for var in self.fitting.predicted] tunits = self.experiment.getTimeUnits().unit else: self.varNameX = 't' self.varNameY = 'C' self.fitting = None self.experiment = None self.protODE = None tunits = unitFromString(self.timeUnits.get()) # Create drug source self.clearGroupParameters() self.createDrugSource() # Create output object self.outputExperiment = PKPDExperiment() self.outputExperiment.general["title"] = "Simulated ODE response" self.outputExperiment.general["comment"] = "Simulated ODE response" # Create the predictor variable tvar = PKPDVariable() tvar.varName = "t" tvar.varType = PKPDVariable.TYPE_NUMERIC tvar.role = PKPDVariable.ROLE_TIME tvar.units = createUnit(tunits) self.outputExperiment.variables[self.varNameX] = tvar # Vias if self.odeSource.get() == self.SRC_ODE: self.outputExperiment.vias = self.experiment.vias else: # "[ViaName]; [ViaType]; [tlag]; [bioavailability]" viaPrmList = [ token for token in self.viaPrm.get().strip().split(',') ] if self.viaType.get() == self.VIATYPE_IV: tokens = [ "Intravenous", "iv", "tlag=0 min", "bioavailability=1" ] elif self.viaType.get() == self.VIATYPE_EV0: tokens = ["Oral", "ev0"] + [ "tlag=" + viaPrmList[-2].strip() + " " + self.timeUnits.get() ] + ["bioavailability=" + viaPrmList[-1].strip()] elif self.viaType.get() == self.VIATYPE_EV1: tokens = ["Oral", "ev1"] + [ "tlag=" + viaPrmList[-2].strip() + " " + self.timeUnits.get() ] + ["bioavailability=" + viaPrmList[-1].strip()] vianame = tokens[0] self.outputExperiment.vias[vianame] = PKPDVia( ptrExperiment=self.outputExperiment) self.outputExperiment.vias[vianame].parseTokens(tokens) # Read the doses dunits = PKPDUnit.UNIT_NONE for line in self.doses.get().replace('\n', ';;').split(';;'): tokens = line.split(';') if len(tokens) < 5: print("Skipping dose: ", line) continue dosename = tokens[0].strip() self.outputExperiment.doses[dosename] = PKPDDose() self.outputExperiment.doses[dosename].parseTokens( tokens, self.outputExperiment.vias) dunits = self.outputExperiment.doses[dosename].getDoseUnits() # Create predicted variables if self.odeSource.get() == self.SRC_ODE: if type(self.fitting.predicted) != list: self.outputExperiment.variables[ self.varNameY] = self.experiment.variables[self.varNameY] else: for varName in self.varNameY: self.outputExperiment.variables[ varName] = self.experiment.variables[varName] else: Cvar = PKPDVariable() Cvar.varName = "C" Cvar.varType = PKPDVariable.TYPE_NUMERIC Cvar.role = PKPDVariable.ROLE_MEASUREMENT Cvar.units = createUnit( divideUnits(dunits.unit, unitFromString(self.volumeUnits.get()))) self.outputExperiment.variables[self.varNameY] = Cvar # Setup model if self.odeSource.get() == self.SRC_ODE: self.model = self.protODE.createModel() if hasattr(self.protODE, "deltaT"): self.model.deltaT = self.protODE.deltaT.get() else: if self.pkType.get() == self.PKTYPE_COMP1: self.model = PK_Monocompartment() elif self.pkType.get() == self.PKTYPE_COMP2: self.model = PK_Twocompartment() elif self.pkType.get() == self.PKTYPE_COMP2CLCLINT: self.model = PK_TwocompartmentsClintCl() self.model.setExperiment(self.outputExperiment) self.model.setXVar(self.varNameX) self.model.setYVar(self.varNameY) Nsamples = int( math.ceil((self.tF.get() - self.t0.get()) / self.model.deltaT)) + 1 self.model.x = [ self.t0.get() + i * self.model.deltaT for i in range(0, Nsamples) ] self.modelList.append(self.model) auxSample = PKPDSample() auxSample.descriptors = {} auxSample.doseDictPtr = self.outputExperiment.doses auxSample.variableDictPtr = self.outputExperiment.variables auxSample.doseList = self.outputExperiment.doses.keys() auxSample.interpretDose() self.drugSource.setDoses(auxSample.parsedDoseList, self.t0.get() - 10, self.tF.get() + 10) self.model.drugSource = self.drugSource # Check units # Dunits = self.outputExperiment.doses[dosename].dunits # Cunits = self.experiment.variables[self.varNameY].units # Process user parameters if self.odeSource.get() == self.SRC_ODE: if self.paramsSource == ProtPKPDODESimulate.PRM_POPULATION: Nsimulations = self.Nsimulations.get() elif self.paramsSource == ProtPKPDODESimulate.PRM_USER_DEFINED: lines = self.prmUser.get().strip().replace('\n', ';;').split(';;') Nsimulations = len(lines) prmUser = [] for line in lines: tokens = line.strip().split(',') prmUser.append([float(token) for token in tokens]) elif self.paramsSource == ProtPKPDODESimulate.PRM_FITTING: Nsimulations = len(self.fitting.sampleFits) else: self.inputExperiment = self.readExperiment( self.inputExperiment.get().fnPKPD) Nsimulations = len(self.inputExperiment.samples) inputSampleNames = self.inputExperiment.samples.keys() else: lines = self.prmUser.get().strip().replace('\n', ';;').split(';;') Nsimulations = len(lines) prmUser = [] for line in lines: tokens = line.strip().split(',') prmUser.append([float(token) for token in tokens]) # Simulate the different responses simulationsX = self.model.x simulationsY = np.zeros( (Nsimulations, len(simulationsX), self.getResponseDimension())) AUCarray = np.zeros(Nsimulations) AUMCarray = np.zeros(Nsimulations) MRTarray = np.zeros(Nsimulations) CminArray = np.zeros(Nsimulations) CmaxArray = np.zeros(Nsimulations) CavgArray = np.zeros(Nsimulations) CtauArray = np.zeros(Nsimulations) TminArray = np.zeros(Nsimulations) TmaxArray = np.zeros(Nsimulations) TtauArray = np.zeros(Nsimulations) fluctuationArray = np.zeros(Nsimulations) percentageAccumulationArray = np.zeros(Nsimulations) wb = openpyxl.Workbook() wb.active.title = "Simulations" for i in range(0, Nsimulations): self.setTimeRange(None) if self.odeSource.get() == self.SRC_ODE: if self.paramsSource == ProtPKPDODESimulate.PRM_POPULATION: # Take parameters randomly from the population nfit = int(random.uniform(0, len(self.fitting.sampleFits))) sampleFit = self.fitting.sampleFits[nfit] nprm = int(random.uniform(0, sampleFit.parameters.shape[0])) parameters = sampleFit.parameters[nprm, :] self.fromSample = "Population %d" % nprm elif self.paramsSource == ProtPKPDODESimulate.PRM_USER_DEFINED: parameters = np.asarray(prmUser[i], np.double) self.fromSample = "User defined" elif self.paramsSource == ProtPKPDODESimulate.PRM_FITTING: parameters = self.fitting.sampleFits[i].parameters self.fromSample = self.fitting.sampleFits[i].sampleName else: parameters = [] self.fromSample = inputSampleNames[i] sample = self.inputExperiment.samples[self.fromSample] for prmName in self.fitting.modelParameters: parameters.append( float(sample.getDescriptorValue(prmName))) else: parameters = np.asarray(viaPrmList[:-2] + prmUser[i], np.double) self.fromSample = "User defined" print("From sample name: %s" % self.fromSample) print("Simulated sample %d: %s" % (i, str(parameters))) # Prepare source and this object self.drugSource.setDoses(auxSample.parsedDoseList, self.model.t0, self.model.tF) if self.protODE is not None: self.protODE.configureSource(self.drugSource) self.model.drugSource = self.drugSource parameterNames = self.getParameterNames( ) # Necessary to count the number of source and PK parameters # Prepare the model self.setParameters(parameters) y = self.forwardModel(parameters, [simulationsX] * self.getResponseDimension()) # Create AUC, AUMC, MRT variables and units if i == 0: if type(self.varNameY) != list: self.Cunits = self.outputExperiment.variables[ self.varNameY].units else: self.Cunits = self.outputExperiment.variables[ self.varNameY[0]].units self.AUCunits = multiplyUnits(tvar.units.unit, self.Cunits.unit) self.AUMCunits = multiplyUnits(tvar.units.unit, self.AUCunits) if self.addStats or self.addIndividuals: fromvar = PKPDVariable() fromvar.varName = "FromSample" fromvar.varType = PKPDVariable.TYPE_TEXT fromvar.role = PKPDVariable.ROLE_LABEL fromvar.units = createUnit("none") AUCvar = PKPDVariable() AUCvar.varName = "AUC0t" AUCvar.varType = PKPDVariable.TYPE_NUMERIC AUCvar.role = PKPDVariable.ROLE_LABEL AUCvar.units = createUnit(strUnit(self.AUCunits)) AUMCvar = PKPDVariable() AUMCvar.varName = "AUMC0t" AUMCvar.varType = PKPDVariable.TYPE_NUMERIC AUMCvar.role = PKPDVariable.ROLE_LABEL AUMCvar.units = createUnit(strUnit(self.AUMCunits)) MRTvar = PKPDVariable() MRTvar.varName = "MRT" MRTvar.varType = PKPDVariable.TYPE_NUMERIC MRTvar.role = PKPDVariable.ROLE_LABEL MRTvar.units = createUnit( self.outputExperiment.getTimeUnits().unit) Cmaxvar = PKPDVariable() Cmaxvar.varName = "Cmax" Cmaxvar.varType = PKPDVariable.TYPE_NUMERIC Cmaxvar.role = PKPDVariable.ROLE_LABEL Cmaxvar.units = createUnit(strUnit(self.Cunits.unit)) Tmaxvar = PKPDVariable() Tmaxvar.varName = "Tmax" Tmaxvar.varType = PKPDVariable.TYPE_NUMERIC Tmaxvar.role = PKPDVariable.ROLE_LABEL Tmaxvar.units = createUnit( self.outputExperiment.getTimeUnits().unit) Cminvar = PKPDVariable() Cminvar.varName = "Cmin" Cminvar.varType = PKPDVariable.TYPE_NUMERIC Cminvar.role = PKPDVariable.ROLE_LABEL Cminvar.units = createUnit(strUnit(self.Cunits.unit)) Tminvar = PKPDVariable() Tminvar.varName = "Tmin" Tminvar.varType = PKPDVariable.TYPE_NUMERIC Tminvar.role = PKPDVariable.ROLE_LABEL Tminvar.units = createUnit( self.outputExperiment.getTimeUnits().unit) Cavgvar = PKPDVariable() Cavgvar.varName = "Cavg" Cavgvar.varType = PKPDVariable.TYPE_NUMERIC Cavgvar.role = PKPDVariable.ROLE_LABEL Cavgvar.units = createUnit(strUnit(self.Cunits.unit)) self.outputExperiment.variables["FromSample"] = fromvar self.outputExperiment.variables["AUC0t"] = AUCvar self.outputExperiment.variables["AUMC0t"] = AUMCvar self.outputExperiment.variables["MRT"] = MRTvar self.outputExperiment.variables["Cmax"] = Cmaxvar self.outputExperiment.variables["Tmax"] = Tmaxvar self.outputExperiment.variables["Cmin"] = Cminvar self.outputExperiment.variables["Tmin"] = Tminvar self.outputExperiment.variables["Cavg"] = Cavgvar excelWriteRow([ "simulationName", "fromSample", "doseNumber", "AUC [%s]" % strUnit(self.AUCunits), "AUMC [%s]" % strUnit(self.AUMCunits), "Cmin [%s]" % strUnit(self.Cunits.unit), "Cavg [%s]" % strUnit(self.Cunits.unit), "Cmax [%s]" % strUnit(self.Cunits.unit), "Ctau [%s]" % strUnit(self.Cunits.unit), "Tmin [%s]" % strUnit(self.outputExperiment.getTimeUnits().unit), "Tmax [%s]" % strUnit(self.outputExperiment.getTimeUnits().unit), "Ttau [%s]" % strUnit(self.outputExperiment.getTimeUnits().unit) ], wb, 1, bold=True) wbRow = 2 # Evaluate AUC, AUMC and MRT in the last full period AUClist, AUMClist, Cminlist, Cavglist, Cmaxlist, Ctaulist, Tmaxlist, Tminlist, Ttaulist = self.NCA( self.model.x, y[0]) for doseNo in range(0, len(AUClist)): excelWriteRow([ "Simulation_%d" % i, self.fromSample, doseNo, AUClist[doseNo], AUMClist[doseNo], Cminlist[doseNo], Cavglist[doseNo], Cmaxlist[doseNo], Ctaulist[doseNo], Tminlist[doseNo], Tmaxlist[doseNo], Ttaulist[doseNo] ], wb, wbRow) wbRow += 1 # Keep results for j in range(self.getResponseDimension()): simulationsY[i, :, j] = y[j] AUCarray[i] = self.AUC0t AUMCarray[i] = self.AUMC0t MRTarray[i] = self.MRT CminArray[i] = self.Cmin CmaxArray[i] = self.Cmax CavgArray[i] = self.Cavg CtauArray[i] = self.Ctau TminArray[i] = self.Tmin TmaxArray[i] = self.Tmax TtauArray[i] = self.Ttau fluctuationArray[i] = self.fluctuation percentageAccumulationArray[i] = self.percentageAccumulation if self.addIndividuals or self.paramsSource != ProtPKPDODESimulate.PRM_POPULATION: self.addSample("Simulation_%d" % i, dosename, simulationsX, y[0]) # Report NCA statistics fhSummary = open(self._getPath("summary.txt"), "w") alpha_2 = (100 - self.confidenceLevel.get()) / 2 limits = np.percentile(AUCarray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "AUC %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.AUCunits), np.mean(AUCarray))) limits = np.percentile(AUMCarray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "AUMC %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.AUMCunits), np.mean(AUMCarray))) limits = np.percentile(MRTarray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "MRT %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.outputExperiment.getTimeUnits().unit), np.mean(MRTarray))) limits = np.percentile(CminArray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Cmin %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.Cunits.unit), np.mean(CminArray))) limits = np.percentile(CmaxArray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Cmax %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.Cunits.unit), np.mean(CmaxArray))) limits = np.percentile(CavgArray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Cavg %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.Cunits.unit), np.mean(CavgArray))) limits = np.percentile(CtauArray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Ctau %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.Cunits.unit), np.mean(CtauArray))) limits = np.percentile(TminArray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Tmin %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.outputExperiment.getTimeUnits().unit), np.mean(TminArray))) limits = np.percentile(TmaxArray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Tmax %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.outputExperiment.getTimeUnits().unit), np.mean(TmaxArray))) limits = np.percentile(TtauArray, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Ttau %f%% confidence interval=[%f,%f] [%s] mean=%f" % (self.confidenceLevel.get(), limits[0], limits[1], strUnit(self.outputExperiment.getTimeUnits().unit), np.mean(TtauArray))) aux = fluctuationArray[~np.isnan(fluctuationArray)] if len(aux) > 0: limits = np.percentile(aux, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Fluctuation %f%% confidence interval=[%f,%f] [%%] mean=%f" % (self.confidenceLevel.get(), limits[0] * 100, limits[1] * 100, np.mean(aux) * 100)) aux = percentageAccumulationArray[~np.isnan(percentageAccumulationArray )] limits = np.percentile(aux, [alpha_2, 100 - alpha_2]) self.doublePrint( fhSummary, "Accum(1) %f%% confidence interval=[%f,%f] [%%] mean=%f" % (self.confidenceLevel.get(), limits[0] * 100, limits[1] * 100, np.mean(aux) * 100)) fhSummary.close() # Calculate statistics if self.addStats and self.odeSource == 0 and self.paramsSource == 0: if self.paramsSource != ProtPKPDODESimulate.PRM_USER_DEFINED: limits = np.percentile(simulationsY, [alpha_2, 100 - alpha_2], axis=0) print("Lower limit NCA") self.NCA(simulationsX, limits[0]) self.fromSample = "LowerLimit" self.addSample("LowerLimit", dosename, simulationsX, limits[0]) print("Mean profile NCA") if self.getResponseDimension() == 1: mu = np.mean(simulationsY, axis=0) self.NCA(simulationsX, mu) else: mu = [] for j in range(self.getResponseDimension()): mu.append(np.mean(simulationsY[:, :, j], axis=0)) self.NCA(simulationsX, mu[0]) self.fromSample = "Mean" self.addSample("Mean", dosename, simulationsX, mu) if self.paramsSource != ProtPKPDODESimulate.PRM_USER_DEFINED: print("Upper limit NCA") self.NCA(simulationsX, limits[1]) self.fromSample = "UpperLimit" self.addSample("UpperLimit", dosename, simulationsX, limits[1]) self.outputExperiment.write(self._getPath("experiment.pkpd")) wb.save(self._getPath("nca.xlsx"))
def runSimulation(self): self.deposition = PKDepositionParameters() self.deposition.setFiles(self.ptrDeposition.get().fnSubstance.get(), self.ptrDeposition.get().fnLung.get(), self.ptrDeposition.get().fnDeposition.get()) self.deposition.doseMultiplier = self.doseMultiplier.get() self.deposition.read() substanceParams = PKSubstanceLungParameters() substanceParams.multiplier = [ float(x) for x in self.substanceMultiplier.get().split() ] substanceParams.read(self.ptrDeposition.get().fnSubstance.get()) lungParams = PKPhysiologyLungParameters() lungParams.multiplier = [ float(x) for x in self.physiologyMultiplier.get().split() ] lungParams.read(self.ptrDeposition.get().fnLung.get()) pkParams = PKPDExperiment() pkParams.load(self.ptrPK.get().fnPKPD) pkLungParams = PKLung() pkLungParams.prepare( substanceParams, lungParams, pkParams, [float(x) for x in self.pkMultiplier.get().split()], self.ciliarySpeedType.get()) # diameters = np.concatenate((np.arange(0.1,1.1,0.1),np.arange(1.2,9.2,0.2))) # [um] evalStr = "np.concatenate((" + ",".join([ "np.arange(" + x.strip() + ")" for x in self.diameters.get().split(";") ]) + "))" diameters = eval(evalStr, {'np': np}) Sbnd = self.volMultiplier.get() * diam2vol(diameters) tt = np.arange(0, self.simulationTime.get() + self.deltaT.get(), self.deltaT.get()) sol = saturable_2D_upwind_IE(lungParams, pkLungParams, self.deposition, tt, Sbnd) # Postprocessing depositionData = self.deposition.getData() alvDose = np.sum(depositionData['alveolar']) bronchDose = np.sum(depositionData['bronchial']) lungDose = alvDose + bronchDose Aalvsolid = sol['A']['alv']['solid'] Aalvfluid = sol['A']['alv']['fluid'] Aalvtissue = sol['A']['alv']['tissue'] AsysGut = sol['A']['sys']['gut'] AsysPer = sol['A']['sys']['per'] AsysCtr = sol['A']['sys']['ctr'] Atisbr = sol['A']['br']['tissue'] Abrtissue = Atisbr Vtisbr = lungParams.getBronchial()['fVol'] * lungParams.getSystemic( )['OWlung'] Cavgbr = Atisbr / Vtisbr Abrcleared = sol['A']['br']['clear'] Abrcleared = np.reshape(Abrcleared, Abrcleared.size) Abrsolid = sol['A']['br']['solid'] Abrfluid = sol['A']['br']['fluid'] Acleared = sol['A']['sys']['clear'] + AsysGut - AsysGut[0] lungRetention = 100 * (lungDose - Acleared) / lungDose # in percent of lung dose Csysnmol = sol['C']['sys']['ctr'] Csys = Csysnmol * substanceParams.getData()['MW'] CsysPer = AsysPer * substanceParams.getData( )['MW'] / pkLungParams.pkData['Vp'] # Create output self.experimentLungRetention = PKPDExperiment() self.experimentLungRetention.general["title"] = "Inhalation simulate" tvar = PKPDVariable() tvar.varName = "t" tvar.varType = PKPDVariable.TYPE_NUMERIC tvar.role = PKPDVariable.ROLE_TIME tvar.units = createUnit("min") Rvar = PKPDVariable() Rvar.varName = "Retention" Rvar.varType = PKPDVariable.TYPE_NUMERIC Rvar.role = PKPDVariable.ROLE_MEASUREMENT Rvar.units = createUnit("none") Rvar.comment = "Lung retention (% lung dose)" Cnmolvar = PKPDVariable() Cnmolvar.varName = "Cnmol" Cnmolvar.varType = PKPDVariable.TYPE_NUMERIC Cnmolvar.role = PKPDVariable.ROLE_MEASUREMENT Cnmolvar.units = createUnit("nmol/mL") Cnmolvar.comment = "Central compartment concentration" Cvar = PKPDVariable() Cvar.varName = "C" Cvar.varType = PKPDVariable.TYPE_NUMERIC Cvar.role = PKPDVariable.ROLE_MEASUREMENT Cvar.units = createUnit("g/mL") Cvar.comment = "Central compartment concentration" alvTissueVar = PKPDVariable() alvTissueVar.varName = "alvTissue" alvTissueVar.varType = PKPDVariable.TYPE_NUMERIC alvTissueVar.role = PKPDVariable.ROLE_MEASUREMENT alvTissueVar.units = createUnit("nmol") alvTissueVar.comment = "Amount in alveoli" alvSolidVar = PKPDVariable() alvSolidVar.varName = "alvSolid" alvSolidVar.varType = PKPDVariable.TYPE_NUMERIC alvSolidVar.role = PKPDVariable.ROLE_MEASUREMENT alvSolidVar.units = createUnit("nmol") alvSolidVar.comment = "Amount undissolved in alveoli" alvFluidVar = PKPDVariable() alvFluidVar.varName = "alvFluid" alvFluidVar.varType = PKPDVariable.TYPE_NUMERIC alvFluidVar.role = PKPDVariable.ROLE_MEASUREMENT alvFluidVar.units = createUnit("nmol") alvFluidVar.comment = "Amount in alveolar lining fluid" brTissueVar = PKPDVariable() brTissueVar.varName = "brTissue" brTissueVar.varType = PKPDVariable.TYPE_NUMERIC brTissueVar.role = PKPDVariable.ROLE_MEASUREMENT brTissueVar.units = createUnit("nmol") brTissueVar.comment = "Amount in bronchii" brSolidVar = PKPDVariable() brSolidVar.varName = "brSolid" brSolidVar.varType = PKPDVariable.TYPE_NUMERIC brSolidVar.role = PKPDVariable.ROLE_MEASUREMENT brSolidVar.units = createUnit("nmol") brSolidVar.comment = "Amount undissolved in bronchii" brFluidVar = PKPDVariable() brFluidVar.varName = "brFluid" brFluidVar.varType = PKPDVariable.TYPE_NUMERIC brFluidVar.role = PKPDVariable.ROLE_MEASUREMENT brFluidVar.units = createUnit("nmol") brFluidVar.comment = "Amount in bronchial lining fluid" brClvar = PKPDVariable() brClvar.varName = "brClear" brClvar.varType = PKPDVariable.TYPE_NUMERIC brClvar.role = PKPDVariable.ROLE_MEASUREMENT brClvar.units = createUnit("nmol") brClvar.comment = "Cumulative amount cleared by mucociliary elevator" brCTisvar = PKPDVariable() brCTisvar.varName = "CbrTis" brCTisvar.varType = PKPDVariable.TYPE_NUMERIC brCTisvar.role = PKPDVariable.ROLE_MEASUREMENT brCTisvar.units = createUnit("nmol/mL") brCTisvar.comment = "Concentration in bronchial tissue" sysGutVar = PKPDVariable() sysGutVar.varName = "sysAbsorption" sysGutVar.varType = PKPDVariable.TYPE_NUMERIC sysGutVar.role = PKPDVariable.ROLE_MEASUREMENT sysGutVar.units = createUnit("nmol") sysGutVar.comment = "Amount in absorption compartment" sysCtrVar = PKPDVariable() sysCtrVar.varName = "sysCentral" sysCtrVar.varType = PKPDVariable.TYPE_NUMERIC sysCtrVar.role = PKPDVariable.ROLE_MEASUREMENT sysCtrVar.units = createUnit("nmol") sysCtrVar.comment = "Amount in central compartment" sysPerVar = PKPDVariable() sysPerVar.varName = "sysPeripheral" sysPerVar.varType = PKPDVariable.TYPE_NUMERIC sysPerVar.role = PKPDVariable.ROLE_MEASUREMENT sysPerVar.units = createUnit("nmol") sysPerVar.comment = "Amount in peripheral compartment" CsysPerVar = PKPDVariable() CsysPerVar.varName = "Cp" CsysPerVar.varType = PKPDVariable.TYPE_NUMERIC CsysPerVar.role = PKPDVariable.ROLE_MEASUREMENT CsysPerVar.units = createUnit("g/mL") CsysPerVar.comment = "Concentration in peripheral compartment" doseNmolVar = PKPDVariable() doseNmolVar.varName = "dose_nmol" doseNmolVar.varType = PKPDVariable.TYPE_NUMERIC doseNmolVar.role = PKPDVariable.ROLE_LABEL doseNmolVar.units = createUnit("nmol") doseNmolVar.comment = "Input dose in nmol" doseThroatVar = PKPDVariable() doseThroatVar.varName = "throat_dose_nmol" doseThroatVar.varType = PKPDVariable.TYPE_NUMERIC doseThroatVar.role = PKPDVariable.ROLE_LABEL doseThroatVar.units = createUnit("nmol") doseThroatVar.comment = "Throat dose in nmol" doseLungVar = PKPDVariable() doseLungVar.varName = "lung_dose_nmol" doseLungVar.varType = PKPDVariable.TYPE_NUMERIC doseLungVar.role = PKPDVariable.ROLE_LABEL doseLungVar.units = createUnit("nmol") doseLungVar.comment = "Lung dose in nmol" doseBronchialVar = PKPDVariable() doseBronchialVar.varName = "bronchial_dose_nmol" doseBronchialVar.varType = PKPDVariable.TYPE_NUMERIC doseBronchialVar.role = PKPDVariable.ROLE_LABEL doseBronchialVar.units = createUnit("nmol") doseBronchialVar.comment = "Bronchial dose in nmol" doseAlveolarVar = PKPDVariable() doseAlveolarVar.varName = "alveolar_dose_nmol" doseAlveolarVar.varType = PKPDVariable.TYPE_NUMERIC doseAlveolarVar.role = PKPDVariable.ROLE_LABEL doseAlveolarVar.units = createUnit("nmol") doseAlveolarVar.comment = "Alveolar dose in nmol" mccClearedLungDoseFractionVar = PKPDVariable() mccClearedLungDoseFractionVar.varName = "mcc_cleared_lung_dose_fraction" mccClearedLungDoseFractionVar.varType = PKPDVariable.TYPE_NUMERIC mccClearedLungDoseFractionVar.role = PKPDVariable.ROLE_LABEL mccClearedLungDoseFractionVar.units = createUnit("None") mccClearedLungDoseFractionVar.comment = "MCC cleared lung dose fraction" self.experimentLungRetention.variables["t"] = tvar self.experimentLungRetention.variables["Retention"] = Rvar self.experimentLungRetention.variables["Cnmol"] = Cnmolvar self.experimentLungRetention.variables["C"] = Cvar self.experimentLungRetention.variables["alvTissue"] = alvTissueVar self.experimentLungRetention.variables["alvFluid"] = alvFluidVar self.experimentLungRetention.variables["alvSolid"] = alvSolidVar self.experimentLungRetention.variables["brTissue"] = brTissueVar self.experimentLungRetention.variables["brFluid"] = brFluidVar self.experimentLungRetention.variables["brSolid"] = brSolidVar self.experimentLungRetention.variables["brClear"] = brClvar self.experimentLungRetention.variables["CbrTis"] = brCTisvar self.experimentLungRetention.variables["sysCentral"] = sysCtrVar self.experimentLungRetention.variables["sysAbsoprtion"] = sysGutVar self.experimentLungRetention.variables["sysPeripheral"] = sysPerVar self.experimentLungRetention.variables["Cp"] = CsysPerVar self.experimentLungRetention.variables["dose_nmol"] = doseNmolVar self.experimentLungRetention.variables[ "throat_dose_nmol"] = doseThroatVar self.experimentLungRetention.variables["lung_dose_nmol"] = doseLungVar self.experimentLungRetention.variables[ "bronchial_dose_nmol"] = doseBronchialVar self.experimentLungRetention.variables[ "alveolar_dose_nmol"] = doseAlveolarVar self.experimentLungRetention.variables[ "mcc_cleared_lung_dose_fraction"] = mccClearedLungDoseFractionVar # Samples simulationSample = PKPDSample() simulationSample.sampleName = "simulation" simulationSample.addMeasurementColumn("t", tt) simulationSample.addMeasurementColumn("Retention", lungRetention) simulationSample.addMeasurementColumn("Cnmol", Csysnmol) simulationSample.addMeasurementColumn("C", Csys) simulationSample.addMeasurementColumn("alvFluid", Aalvfluid) simulationSample.addMeasurementColumn("alvTissue", Aalvtissue) simulationSample.addMeasurementColumn("alvSolid", Aalvsolid) simulationSample.addMeasurementColumn("brFluid", Abrfluid) simulationSample.addMeasurementColumn("brTissue", Abrtissue) simulationSample.addMeasurementColumn("brSolid", Abrsolid) simulationSample.addMeasurementColumn("brClear", Abrcleared) simulationSample.addMeasurementColumn("CbrTis", Cavgbr) simulationSample.addMeasurementColumn("sysAbsorption", AsysGut) simulationSample.addMeasurementColumn("sysCentral", AsysCtr) simulationSample.addMeasurementColumn("sysPeripheral", AsysPer) simulationSample.addMeasurementColumn("Cp", CsysPer) simulationSample.setDescriptorValue("dose_nmol", depositionData['dose_nmol']) simulationSample.setDescriptorValue("throat_dose_nmol", depositionData['throat']) lungDose = depositionData['dose_nmol'] - depositionData['throat'] simulationSample.setDescriptorValue("lung_dose_nmol", lungDose) simulationSample.setDescriptorValue("bronchial_dose_nmol", bronchDose) simulationSample.setDescriptorValue("alveolar_dose_nmol", alvDose) simulationSample.setDescriptorValue("mcc_cleared_lung_dose_fraction", Abrcleared[-1] / lungDose) self.experimentLungRetention.samples[ "simulmvarNameation"] = simulationSample self.experimentLungRetention.write(self._getPath("experiment.pkpd")) # Plots import matplotlib.pyplot as plt lungData = lungParams.getBronchial() Xbnd = np.sort([0] + lungData['end_cm'].tolist() + lungData['pos'].tolist()) Xctr = Xbnd[:-1] + np.diff(Xbnd) / 2 tvec = tt / 60 T = np.max(tvec) Cflu = sol['C']['br']['fluid'] Cs = substanceParams.getData()['Cs_br'] plt.figure(figsize=(15, 9)) plt.title('Concentration in bronchial fluid (Cs=%f [uM])' % Cs) plt.imshow(Cflu, interpolation='bilinear', aspect='auto', extent=[np.min(Xctr), np.max(Xctr), T, 0]) plt.clim(0, Cs) plt.xlim(np.min(Xctr), np.max(Xctr)) plt.ylim(0, T) plt.colorbar() plt.ylabel('Time [h]') plt.xlabel('Distance from throat [cm]') plt.savefig(self._getPath('concentrationBronchialFluid.png')) Ctis = sol['C']['br']['fluid'] plt.figure(figsize=(15, 9)) plt.title('Concentration in bronchial tissue') plt.imshow(Ctis, interpolation='bilinear', aspect='auto', extent=[np.min(Xctr), np.max(Xctr), T, 0]) plt.xlim(np.min(Xctr), np.max(Xctr)) plt.ylim(0, T) plt.colorbar() plt.ylabel('Time [h]') plt.xlabel('Distance from throat [cm]') plt.savefig(self._getPath('concentrationBronchialTissue.png'))
def runFilter(self, objId, filterType, condition): import copy experiment = self.readExperiment(self.inputExperiment.get().fnPKPD) self.printSection("Filtering") if self.filterType.get() == 0: filterType = "exclude" elif self.filterType.get() == 1: filterType = "keep" elif self.filterType.get() == 2: filterType = "rmNA" elif self.filterType.get() == 3: filterType = "rmLL" elif self.filterType.get() == 4: filterType = "subsLL" elif self.filterType.get() == 5: filterType = "subsUL" filteredExperiment = PKPDExperiment() filteredExperiment.general = copy.copy(experiment.general) filteredExperiment.variables = copy.copy(experiment.variables) filteredExperiment.samples = {} filteredExperiment.doses = {} filteredExperiment.vias = {} usedDoses = [] for sampleKey, sample in experiment.samples.items(): candidateSample = PKPDSample() candidateSample.variableDictPtr = copy.copy(sample.variableDictPtr) candidateSample.doseDictPtr = copy.copy(sample.doseDictPtr) candidateSample.sampleName = copy.copy(sample.sampleName) candidateSample.doseList = copy.copy(sample.doseList) candidateSample.descriptors = copy.copy(sample.descriptors) candidateSample.measurementPattern = copy.copy( sample.measurementPattern) N = 0 # Number of initial measurements if len(sample.measurementPattern) > 0: aux = getattr(sample, "measurement_%s" % sample.measurementPattern[0]) N = len(aux) if N == 0: continue # Create empty output variables Nvar = len(sample.measurementPattern) convertToFloat = [] for i in range(0, Nvar): exec("candidateSample.measurement_%s = []" % sample.measurementPattern[i]) convertToFloat.append( sample.variableDictPtr[sample.measurementPattern[i]]. varType == PKPDVariable.TYPE_NUMERIC) for n in range(0, N): toAdd = [] okToAddTimePoint = True conditionPython = copy.copy(condition) for i in range(0, Nvar): ldict = {} exec( "aux=sample.measurement_%s[%d]" % (sample.measurementPattern[i], n), locals(), ldict) aux = ldict['aux'] if filterType == "rmNA": if aux == "NA" or aux == "None": okToAddTimePoint = False else: toAdd.append(aux) elif filterType == "rmLL": if aux == "LLOQ" or aux == "ULOQ": okToAddTimePoint = False else: toAdd.append(aux) elif filterType == "subsLL": okToAddTimePoint = True if aux == "LLOQ": toAdd.append(str(self.substitute.get())) else: toAdd.append(aux) elif filterType == "subsUL": okToAddTimePoint = True if aux == "ULOQ": toAdd.append(str(self.substitute.get())) else: toAdd.append(aux) else: # Keep or exclude toAdd.append(aux) varString = "$(%s)" % sample.measurementPattern[i] if varString in conditionPython: if aux == "NA": okToAddTimePoint = False else: if convertToFloat[i]: conditionPython = conditionPython.replace( varString, "%f" % float(aux)) else: conditionPython = conditionPython.replace( varString, "'%s'" % aux) if (filterType == "exclude" or filterType == "keep") and okToAddTimePoint: okToAddTimePoint = eval(conditionPython, {"__builtins__": None}, {}) if filterType == "exclude": okToAddTimePoint = not okToAddTimePoint if okToAddTimePoint: for i in range(0, Nvar): exec("candidateSample.measurement_%s.append('%s')" % (sample.measurementPattern[i], toAdd[i])) N = len( getattr(sample, "measurement_%s" % sample.measurementPattern[0] )) # Number of final measurements if N != 0: filteredExperiment.samples[ candidateSample.sampleName] = candidateSample for doseName in candidateSample.doseList: if not doseName in usedDoses: usedDoses.append(doseName) if len(usedDoses) > 0: for doseName in usedDoses: filteredExperiment.doses[doseName] = copy.copy( experiment.doses[doseName]) viaName = experiment.doses[doseName].via.viaName if not viaName in filteredExperiment.vias: filteredExperiment.vias[viaName] = copy.copy( experiment.vias[viaName]) self.writeExperiment(filteredExperiment, self._getPath("experiment.pkpd")) self.experiment = filteredExperiment
def addSample(self, sampleName, doseList, simulationsX, y): newSample = PKPDSample() newSample.sampleName = sampleName newSample.variableDictPtr = self.outputExperiment.variables newSample.doseDictPtr = self.outputExperiment.doses newSample.descriptors = {} newSample.doseList = doseList if type(self.varNameY) != list: newSample.addMeasurementPattern([self.varNameY]) newSample.addMeasurementColumn("t", simulationsX) newSample.addMeasurementColumn(self.varNameY, y) else: for j in range(len(self.varNameY)): newSample.addMeasurementPattern([self.varNameY[j]]) newSample.addMeasurementColumn("t", simulationsX) for j in range(len(self.varNameY)): newSample.addMeasurementColumn(self.varNameY[j], y[j]) self.outputExperiment.samples[sampleName] = newSample
def runSimulate(self): tvar = PKPDVariable() tvar.varName = "t" tvar.varType = PKPDVariable.TYPE_NUMERIC tvar.role = PKPDVariable.ROLE_TIME if self.timeUnits.get() == 0: tvar.units = createUnit("min") elif self.timeUnits.get() == 1: tvar.units = createUnit("h") Avar = PKPDVariable() Avar.varName = "A" Avar.varType = PKPDVariable.TYPE_NUMERIC Avar.role = PKPDVariable.ROLE_MEASUREMENT if self.AUnits.get() != "%": Avar.units = createUnit(self.AUnits.get()) else: Avar.units = createUnit("none") self.experimentSimulated = PKPDExperiment() self.experimentSimulated.variables["t"] = tvar self.experimentSimulated.variables["A"] = Avar self.experimentSimulated.general[ "title"] = "Simulated dissolution profile" self.experimentSimulated.general["comment"] = "" if self.modelType.get() == 0: self.model = Dissolution0() elif self.modelType.get() == 1: self.model = Dissolution1() elif self.modelType.get() == 2: self.model = DissolutionAlpha() elif self.modelType.get() == 3: self.model = DissolutionWeibull() elif self.modelType.get() == 4: self.model = DissolutionDoubleWeibull() elif self.modelType.get() == 5: self.model = DissolutionTripleWeibull() elif self.modelType.get() == 6: self.model = DissolutionHiguchi() elif self.modelType.get() == 7: self.model = DissolutionKorsmeyer() elif self.modelType.get() == 8: self.model = DissolutionHixson() elif self.modelType.get() == 9: self.model = DissolutionHopfenberg() elif self.modelType.get() == 10: self.model = DissolutionHill() elif self.modelType.get() == 11: self.model = DissolutionMakoidBanakar() elif self.modelType.get() == 12: self.model = DissolutionSplines2() elif self.modelType.get() == 13: self.model = DissolutionSplines3() elif self.modelType.get() == 14: self.model = DissolutionSplines4() elif self.modelType.get() == 15: self.model = DissolutionSplines5() elif self.modelType.get() == 16: self.model = DissolutionSplines6() elif self.modelType.get() == 17: self.model = DissolutionSplines7() elif self.modelType.get() == 18: self.model = DissolutionSplines8() elif self.modelType.get() == 19: self.model = DissolutionSplines9() elif self.modelType.get() == 20: self.model = DissolutionSplines10() self.model.allowTlag = self.allowTlag.get() self.model.parameters = [ float(x) for x in self.parameters.get().split(';') ] newSample = PKPDSample() newSample.sampleName = "simulatedProfile" newSample.variableDictPtr = self.experimentSimulated.variables newSample.descriptors = {} newSample.addMeasurementPattern(["A"]) t0 = self.resampleT0.get() tF = self.resampleTF.get() deltaT = self.resampleT.get() t = np.arange(t0, tF + deltaT, deltaT) self.model.setExperiment(self.experimentSimulated) self.model.setXVar("t") self.model.setYVar("A") self.model.calculateParameterUnits(newSample) y = self.model.forwardModel(self.model.parameters, t) newSample.addMeasurementColumn("t", t) newSample.addMeasurementColumn("A", y[0]) self.experimentSimulated.samples[newSample.sampleName] = newSample fnExperiment = self._getPath("experimentSimulated.pkpd") self.experimentSimulated.write(fnExperiment) self.fittingSimulated = PKPDFitting() self.fittingSimulated.fnExperiment.set(fnExperiment) self.fittingSimulated.predictor = self.experimentSimulated.variables[ "t"] self.fittingSimulated.predicted = self.experimentSimulated.variables[ "A"] self.fittingSimulated.modelDescription = self.model.getDescription() self.fittingSimulated.modelParameters = self.model.getParameterNames() self.fittingSimulated.modelParameterUnits = self.model.parameterUnits sampleFit = PKPDSampleFit() sampleFit.sampleName = newSample.sampleName sampleFit.x = [t] sampleFit.y = y sampleFit.yp = y sampleFit.yl = y sampleFit.yu = y sampleFit.parameters = self.model.parameters sampleFit.modelEquation = self.model.getEquation() sampleFit.R2 = -1 sampleFit.R2adj = -1 sampleFit.AIC = -1 sampleFit.AICc = -1 sampleFit.BIC = -1 sampleFit.significance = ["NA" for prm in sampleFit.parameters] sampleFit.lowerBound = ["NA" for prm in sampleFit.parameters] sampleFit.upperBound = ["NA" for prm in sampleFit.parameters] self.fittingSimulated.sampleFits.append(sampleFit) fnFitting = self._getPath("fittingSimulated.pkpd") self.fittingSimulated.write(fnFitting)
def addSample(self, sampleName, t, y): newSample = PKPDSample() newSample.sampleName = sampleName newSample.variableDictPtr = self.outputExperiment.variables newSample.descriptors = {} newSample.addMeasurementPattern(["A"]) tUnique, yUnique = twoWayUniqueFloatValues(t,y) newSample.addMeasurementColumn("t", tUnique) newSample.addMeasurementColumn("A",yUnique) self.outputExperiment.samples[sampleName] = newSample
def runSimulate(self): # Take first experiment self.protODE = self.inputODEs[0].get() if hasattr(self.protODE, "outputExperiment"): self.experiment = self.readExperiment( self.protODE.outputExperiment.fnPKPD, show=False) elif hasattr(self.protODE, "outputExperiment1"): self.experiment = self.readExperiment( self.protODE.outputExperiment1.fnPKPD, show=False) else: raise Exception("Cannot find an outputExperiment in the input ODE") if hasattr(self.protODE, "outputFitting"): self.fitting = self.readFitting( self.protODE.outputFitting.fnFitting, show=False) elif hasattr(self.protODE, "outputFitting1"): self.fitting = self.readFitting( self.protODE.outputFitting1.fnFitting, show=False) self.varNameX = self.fitting.predictor.varName if type(self.fitting.predicted) != list: self.varNameY = self.fitting.predicted.varName else: self.varNameY = [var.varName for var in self.fitting.predicted] # Create output object self.outputExperiment = PKPDExperiment() tvar = PKPDVariable() tvar.varName = "t" tvar.varType = PKPDVariable.TYPE_NUMERIC tvar.role = PKPDVariable.ROLE_TIME tvar.units = createUnit(self.experiment.getTimeUnits().unit) Nsamples = int( math.ceil((self.tF.get() - self.t0.get()) / self.deltaT.get())) + 1 if tvar.units == PKPDUnit.UNIT_TIME_MIN: Nsamples *= 60 self.outputExperiment.variables[self.varNameX] = tvar if type(self.fitting.predicted) != list: self.outputExperiment.variables[ self.varNameY] = self.experiment.variables[self.varNameY] else: for varName in self.varNameY: self.outputExperiment.variables[ varName] = self.experiment.variables[varName] self.outputExperiment.general["title"] = "Simulated ODE response" self.outputExperiment.general["comment"] = "Simulated ODE response" self.outputExperiment.vias = self.experiment.vias # Read the doses doseLines = [] for line in self.doses.get().replace('\n', ';;').split(';;'): doseLines.append(line) doseIdx = 0 simulationsY = None doseList = [] for protODEPtr in self.inputODEs: self.protODE = protODEPtr.get() if hasattr(self.protODE, "outputExperiment"): self.experiment = self.readExperiment( self.protODE.outputExperiment.fnPKPD, show=False) elif hasattr(self.protODE, "outputExperiment1"): self.experiment = self.readExperiment( self.protODE.outputExperiment1.fnPKPD, show=False) else: raise Exception( "Cannot find an outputExperiment in the input ODE") if hasattr(self.protODE, "outputFitting"): self.fitting = self.readFitting( self.protODE.outputFitting.fnFitting, show=False) elif hasattr(self.protODE, "outputFitting1"): self.fitting = self.readFitting( self.protODE.outputFitting1.fnFitting, show=False) for viaName in self.experiment.vias: if not viaName in self.outputExperiment.vias: self.outputExperiment.vias[viaName] = copy.copy( self.experiment.vias[viaName]) # Create drug source self.clearGroupParameters() self.createDrugSource() # Setup model self.model = self.protODE.createModel() self.model.setExperiment(self.outputExperiment) self.model.deltaT = self.deltaT.get() self.model.setXVar(self.varNameX) self.model.setYVar(self.varNameY) self.model.x = [ self.t0.get() + i * self.model.deltaT for i in range(0, Nsamples) ] self.modelList.append(self.model) tokens = doseLines[doseIdx].split(';') if len(tokens) < 5: print("Skipping dose: ", line) continue dosename = tokens[0].strip() self.outputExperiment.doses[dosename] = PKPDDose() self.outputExperiment.doses[dosename].parseTokens( tokens, self.outputExperiment.vias) doseList.append(dosename) auxSample = PKPDSample() auxSample.descriptors = {} auxSample.doseDictPtr = self.outputExperiment.doses auxSample.variableDictPtr = self.outputExperiment.variables auxSample.doseList = [dosename] auxSample.interpretDose() self.drugSource.setDoses(auxSample.parsedDoseList, self.t0.get() - 10, self.tF.get() + 10) self.model.drugSource = self.drugSource # Simulate the different responses simulationsX = self.model.x self.setTimeRange(None) parameters = self.fitting.sampleFits[0].parameters print("Input model: %s" % self.protODE.getObjLabel()) print("Sample name: %s" % self.fitting.sampleFits[0].sampleName) print("Parameters: ", parameters) print("Dose: %s" % doseLines[doseIdx]) print(" ") # Prepare source and this object self.protODE.configureSource(self.drugSource) parameterNames = self.getParameterNames( ) # Necessary to count the number of source and PK parameters # Prepare the model y = self.forwardModel(parameters, [simulationsX] * self.getResponseDimension()) # Keep results if simulationsY is None: simulationsY = copy.copy(y) else: for j in range(self.getResponseDimension()): simulationsY[j] += y[j] doseIdx += 1 self.addSample("Simulation", doseList, simulationsX, simulationsY[0]) self.outputExperiment.write(self._getPath("experiment.pkpd"))
def addSample(self, sampleName, t, y, fromSamples): newSample = PKPDSample() newSample.sampleName = sampleName newSample.variableDictPtr = self.outputExperiment.variables newSample.doseDictPtr = self.outputExperiment.doses newSample.descriptors = {} newSample.doseList = ["Bolus"] newSample.addMeasurementPattern([self.fittingPK.predicted.varName]) newSample.addMeasurementColumn("t", t) newSample.addMeasurementColumn(self.fittingPK.predicted.varName, y) newSample.descriptors["AUC0t"] = self.AUC0t newSample.descriptors["AUMC0t"] = self.AUMC0t newSample.descriptors["MRT"] = self.MRT newSample.descriptors["Cmax"] = self.Cmax newSample.descriptors["Tmax"] = self.Tmax self.outputExperiment.samples[sampleName] = newSample self.outputExperiment.addLabelToSample(sampleName, "from", "individual---vesel", fromSamples)
def addSample(self, samplename, tokens): if not samplename in self.experiment.samples.keys(): self.experiment.samples[samplename] = PKPDSample() self.experiment.samples[samplename].parseTokens( tokens, self.experiment.variables, self.experiment.doses, self.experiment.groups)
def addSample(self, sampleName, doseName, simulationsX, y): newSample = PKPDSample() newSample.sampleName = sampleName newSample.variableDictPtr = self.outputExperiment.variables newSample.doseDictPtr = self.outputExperiment.doses newSample.descriptors = {} newSample.doseList = [doseName] tsample = np.arange(0.0, np.max(simulationsX), self.sampling.get()) if type(self.varNameY) != list: newSample.addMeasurementPattern([self.varNameY]) B = InterpolatedUnivariateSpline(simulationsX, y, k=1) newSample.addMeasurementColumn("t", tsample) newSample.addMeasurementColumn(self.varNameY, B(tsample)) else: for j in range(len(self.varNameY)): newSample.addMeasurementPattern([self.varNameY[j]]) newSample.addMeasurementColumn("t", tsample) for j in range(len(self.varNameY)): B = InterpolatedUnivariateSpline(simulationsX, y[j], k=1) newSample.addMeasurementColumn(self.varNameY[j], B(tsample)) newSample.descriptors["FromSample"] = self.fromSample newSample.descriptors["AUC0t"] = self.AUC0t newSample.descriptors["AUMC0t"] = self.AUMC0t newSample.descriptors["MRT"] = self.MRT newSample.descriptors["Cmax"] = self.Cmax newSample.descriptors["Cmin"] = self.Cmin newSample.descriptors["Cavg"] = self.Cavg newSample.descriptors["Tmax"] = self.Tmax newSample.descriptors["Tmin"] = self.Tmin self.outputExperiment.samples[sampleName] = newSample
def postSampleAnalysis(self, sampleName): self.experiment.addParameterToSample( sampleName, "tvitroMax", self.experiment.variables[self.varNameX].units.unit, "Maximum tvitro for which this fitting is valid", np.max(self.model.x)) if self.resampleT.get() > 0: newSample = PKPDSample() newSample.sampleName = sampleName + "_simulated" newSample.variableDictPtr = self.experimentSimulated.variables newSample.doseDictPtr = self.experimentSimulated.doses newSample.descriptors = {} newSample.addMeasurementPattern([self.fitting.predicted.varName]) t0 = self.resampleT0.get() tF = self.resampleTF.get() deltaT = self.resampleT.get() if tF == 0: tF = np.max(self.model.x) t = np.arange(t0, tF + deltaT, deltaT) y = self.model.forwardModel(self.model.parameters, t) newSample.addMeasurementColumn(self.fitting.predictor.varName, t) newSample.addMeasurementColumn(self.fitting.predicted.varName, y[0]) self.experimentSimulated.samples[sampleName] = newSample
def addSample(self, set, sampleName, individualFrom, vesselFrom, optimum, R): # Remove NANs idx = np.isnan(self.tvitroReinterpolated) idx = np.logical_or(idx, np.isnan(self.AdissolReinterpolated)) idx = np.logical_or(idx, np.isnan(self.FabsPredicted)) newSampleFabs = PKPDSample() newSampleFabs.sampleName = sampleName newSampleFabs.variableDictPtr = self.outputExperimentFabsSingle.variables newSampleFabs.descriptors = {} newSampleFabs.addMeasurementColumn("tvitroReinterpolated", self.tvitroReinterpolated[~idx]) newSampleFabs.addMeasurementColumn("AdissolReinterpolated", self.AdissolReinterpolated[~idx]) newSampleFabs.addMeasurementColumn("tvivo", self.tvivoUnique[~idx]) newSampleFabs.addMeasurementColumn("FabsPredicted", self.FabsPredicted[~idx]) newSampleFabs.addMeasurementColumn("Fabs", self.FabsUnique[~idx]) if set == 1: outputExperiment = self.outputExperimentFabs else: outputExperiment = self.outputExperimentFabsSingle outputExperiment.samples[sampleName] = newSampleFabs self.addParametersToExperiment(outputExperiment, sampleName, individualFrom, vesselFrom, optimum, R) if set == 1: newSampleAdissol = PKPDSample() newSampleAdissol.sampleName = sampleName newSampleAdissol.variableDictPtr = self.outputExperimentAdissol.variables newSampleAdissol.descriptors = {} newSampleAdissol.addMeasurementColumn("tvivoReinterpolated", self.tvivoReinterpolated) newSampleAdissol.addMeasurementColumn("FabsReinterpolated", self.FabsReinterpolated) newSampleAdissol.addMeasurementColumn("tvitro", self.tvitroUnique) newSampleAdissol.addMeasurementColumn("AdissolPredicted", self.AdissolPredicted) newSampleAdissol.addMeasurementColumn("Adissol", self.AdissolUnique) self.outputExperimentAdissol.samples[sampleName] = newSampleAdissol self.addParametersToExperiment(self.outputExperimentAdissol, sampleName, individualFrom, vesselFrom, optimum, R)
def addSample(self, sampleName, individualFrom, vesselFrom, optimum, R, set=1): newSampleFabs = PKPDSample() newSampleFabs.sampleName = sampleName newSampleFabs.variableDictPtr = self.outputExperimentFabs.variables newSampleFabs.descriptors = {} newSampleFabs.addMeasurementColumn("tvitroReinterpolated", self.tvitroReinterpolated) newSampleFabs.addMeasurementColumn("AdissolReinterpolated", self.AdissolReinterpolated) newSampleFabs.addMeasurementColumn("tvivo", self.tvivoUnique) newSampleFabs.addMeasurementColumn("FabsPredicted", self.FabsPredicted) newSampleFabs.addMeasurementColumn("Fabs", self.FabsUnique) if set == 1: self.outputExperimentFabs.samples[sampleName] = newSampleFabs self.addParametersToExperiment(self.outputExperimentFabs, sampleName, individualFrom, vesselFrom, optimum, R) else: self.outputExperimentFabsSingle.samples[sampleName] = newSampleFabs self.addParametersToExperiment(self.outputExperimentFabsSingle, sampleName, individualFrom, vesselFrom, optimum, R) if set == 1: newSampleAdissol = PKPDSample() newSampleAdissol.sampleName = sampleName newSampleAdissol.variableDictPtr = self.outputExperimentAdissol.variables newSampleAdissol.descriptors = {} newSampleAdissol.addMeasurementColumn("tvivoReinterpolated", self.tvivoReinterpolated) newSampleAdissol.addMeasurementColumn("FabsReinterpolated", self.FabsReinterpolated) newSampleAdissol.addMeasurementColumn("tvitro", self.tvitroUnique) newSampleAdissol.addMeasurementColumn("AdissolPredicted", self.AdissolPredicted) newSampleAdissol.addMeasurementColumn("Adissol", self.AdissolUnique) self.outputExperimentAdissol.samples[sampleName] = newSampleAdissol self.addParametersToExperiment(self.outputExperimentAdissol, sampleName, individualFrom, vesselFrom, optimum, R)
def runJoin(self, objId, resampleT): experiment = self.readExperiment(self.inputExperiment.get().fnPKPD) tvarName = experiment.getTimeVariable() mvarNames = experiment.getMeasurementVariables() self.experiment = PKPDExperiment() # General self.experiment.general[ "title"] = "Average of " + experiment.general["title"] if self.condition.get() != "": self.experiment.general[ "title"] += " Condition: %s" % self.condition.get() self.experiment.general["comment"] = copy.copy( experiment.general["comment"]) for key, value in experiment.general.items(): if not (key in self.experiment.general): self.experiment.general[key] = copy.copy(value) # Variables for key, value in experiment.variables.items(): if not (key in self.experiment.variables): self.experiment.variables[key] = copy.copy(value) # Vias for key, value in experiment.vias.items(): if not (key in self.experiment.vias): self.experiment.vias[key] = copy.copy(value) # Doses doseName = None for key, value in experiment.doses.items(): dose = copy.copy(value) self.experiment.doses[dose.doseName] = dose doseName = dose.doseName # Samples self.printSection("Averaging") self.experiment.samples["avg"] = PKPDSample() tokens = ["AverageSample"] if doseName is not None: tokens.append("dose=%s" % doseName) self.experiment.samples["avg"].parseTokens(tokens, self.experiment.variables, self.experiment.doses, self.experiment.groups) for mvarName in mvarNames: allt = {} for sampleName, sample in experiment.getSubGroup( self.condition.get()).items(): t, _ = sample.getXYValues(tvarName, mvarName) t = t[0] # [[...]] -> [...] for i in range(len(t)): ti = float(t[i]) if not ti in allt: allt[ti] = True allt = sorted(allt.keys()) observations = {} for sampleName, sample in experiment.getSubGroup( self.condition.get()).items(): for ti in allt: observations[ti] = [] for sampleName, sample in experiment.getSubGroup( self.condition.get()).items(): print("%s participates in the average" % sampleName) t, y = sample.getXYValues(tvarName, mvarName) t = t[0] # [array] y = y[0] # [array] tUnique, yUnique = uniqueFloatValues(t, y) B = InterpolatedUnivariateSpline(tUnique, yUnique, k=1) mint = np.min(t) maxt = np.max(t) for ti in allt: if ti >= mint and ti <= maxt: observations[ti].append(B(ti)) for ti in observations: if len(observations[ti]) > 0: if self.mode.get() == self.MODE_MEAN: observations[ti] = np.mean(observations[ti]) else: observations[ti] = np.median(observations[ti]) else: observations[ti] = np.nan t = [] yavg = [] for ti in sorted(observations): t.append(ti) yavg.append(observations[ti]) if self.resampleT.get() > 0: t, yavg = uniqueFloatValues(t, yavg) B = InterpolatedUnivariateSpline(t, yavg, k=1) t = np.arange(np.min(t), np.max(t) + self.resampleT.get(), self.resampleT.get()) yavg = B(t) self.experiment.samples["avg"].addMeasurementColumn(tvarName, t) self.experiment.samples["avg"].addMeasurementColumn(mvarName, yavg) print(" ") # Print and save self.writeExperiment(self.experiment, self._getPath("experiment.pkpd"))