Exemple #1
0
    def getSummary(self,fnPKPD):
        experiment = PKPDExperiment()
        experiment.load(fnPKPD)
        self.timeVarName = experiment.getTimeVariable()
        self.CVarName = experiment.getMeasurementVariables()[0] # The first one

        xmin = 1e38
        xmax = -1e38
        for sampleName, sample in experiment.samples.items():
            xValues, _ = self.getPlotValues(sample)
            xmin = min(xmin, min(xValues))
            xmax = max(xmax, max(xValues))

        dataDict = {}  # key will be time values
        xrange = np.arange(xmin, xmax, (xmax - xmin) / 300.0)
        for sampleName, sample in experiment.samples.items():
            xValues, yValues = self.getPlotValues(sample)
            xValuesUnique, yValuesUnique = uniqueFloatValues(xValues, yValues)
            B = InterpolatedUnivariateSpline(xValuesUnique, yValuesUnique, k=1)
            yrange = B(xrange)
            for x, y in izip(xrange, yrange):
                if x in dataDict:
                    dataDict[x].append(y)
                else:
                    dataDict[x] = [y]

        sortedTime = sorted(dataDict.keys())
        # We will store five values (min, 25%, 50%, 75%, max)
        # for each of the time entries computed
        percentileList = [0, 25, 50, 75, 100]
        Y = np.zeros((len(sortedTime), 5))
        for i, t in enumerate(sortedTime):
            Y[i, :] = np.percentile(dataDict[t], percentileList)
        return sortedTime, Y
Exemple #2
0
 def readExperiment(self, fnIn, show=True, fullRead=True):
     experiment = PKPDExperiment()
     experiment.load(fnIn, fullRead=fullRead)
     if show:
         self.printSection("Reading %s" % fnIn)
         experiment._printToStream(sys.stdout)
     return experiment
Exemple #3
0
 def createOutputStep(self):
     newFitting = PKPDFitting()
     newFitting.fnExperiment.set(self.inputExperiment.get().fnPKPD)
     experiment = PKPDExperiment()
     experiment.load(self.inputExperiment.get().fnPKPD)
     for ptrFitting in self.inputFittings:
         newFitting.gather(self.readFitting(ptrFitting.get().fnFitting), experiment)
     self.writeExperiment(newFitting, self._getPath("fitting.pkpd"))
     self._defineOutputs(outputFitting=newFitting)
     for ptrFitting in self.inputFittings:
         self._defineSourceRelation(ptrFitting, newFitting)
Exemple #4
0
    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"))
Exemple #5
0
    def _validate(self):
        retval = []
        if self.twoExperiments.get() == 0:
            experiment1 = PKPDExperiment()
            experiment1.load(self.inputExperiment1.get().fnPKPD,
                             fullRead=False)
            if not self.X1.get() in experiment1.variables:
                retval.append("Cannot find %s in Experiment1" % self.X1.get())
            if not self.Y1.get() in experiment1.variables:
                retval.append("Cannot find %s in Experiment1" % self.Y1.get())

            X2 = self.X1.get() if self.X2.get() == "" else self.X2.get()
            Y2 = self.Y1.get() if self.Y2.get() == "" else self.Y2.get()
            experiment2 = PKPDExperiment()
            experiment2.load(self.inputExperiment2.get().fnPKPD,
                             fullRead=False)
            if not X2 in experiment2.variables:
                retval.append("Cannot find %s in Experiment2" % X2)
            if not Y2 in experiment2.variables:
                retval.append("Cannot find %s in Experiment2" % Y2)
        else:
            for idx, experimentPtr in enumerate(self.inputExperiments):
                experiment = PKPDExperiment()
                experiment.load(experimentPtr.get().fnPKPD, fullRead=False)
                if not self.X1.get() in experiment.variables:
                    retval.append(
                        "Cannot find %s in Experiment whose file is %s" %
                        (self.X1.get(), experimentPtr.fnPKPD))
                if not self.Y1.get() in experiment.variables:
                    retval.append(
                        "Cannot find %s in Experiment whose file is %s" %
                        (self.Y1.get(), experimentPtr.fnPKPD))

        return retval
Exemple #6
0
    def createOutputStep(self):
        fnTmp = self._getExtraPath("aux.pkpd")
        fh = open(fnTmp, "w")

        fh.write("[EXPERIMENT] ===========================\n")
        fh.write("title=%s\n" % self.newTitle.get())
        fh.write("comment=%s\n" % self.newComment.get())
        fh.write("\n")

        fh.write("[VARIABLES] ============================\n")
        fh.write("%s\n" % self.newVariables.get())
        fh.write("\n")

        fh.write("[VIAS] ================================\n")
        fh.write("%s\n" % self.newVias.get())
        fh.write("\n")

        fh.write("[DOSES] ================================\n")
        fh.write("%s\n" % self.newDoses.get())
        fh.write("\n")

        fh.write("[GROUPS] ================================\n")
        fh.write("%s\n" % self.newGroups.get())
        fh.write("\n")

        fh.write("[SAMPLES] ================================\n")
        fh.write("%s\n" % self.newSamples.get())
        fh.write("\n")

        fh.write("[MEASUREMENTS] ===========================\n")
        fh.write("%s\n" % self.newMeasurements.get())
        fh.write("\n")
        fh.close()

        experiment = PKPDExperiment()
        experiment.load(fnTmp, verifyIntegrity=False)

        self.writeExperiment(experiment, self._getPath("experiment.pkpd"))
        self._defineOutputs(outputExperiment=experiment)
Exemple #7
0
    def _validate(self):
        import re
        errors = []
        if self.prefix1.get() == self.prefix2.get():
            experiment1 = PKPDExperiment()
            experiment1.load(self.inputExperiment1.get().fnPKPD)
            experiment2 = PKPDExperiment()
            experiment2.load(self.inputExperiment2.get().fnPKPD)

            # Check if there are repeated doses
            for doseName1 in experiment1.doses:
                if doseName1 in experiment2.doses:
                    errors.append("Dose %s is repeated in both experiments" %
                                  doseName1)

            # Check if there are repeated samples
            for sampleName1 in experiment1.samples:
                if sampleName1 in experiment2.samples:
                    errors.append("Sample %s is repeated in both experiments" %
                                  sampleName1)
        if len(errors) > 0:
            errors.append("Use the prefixes in the Advanced options")
        return errors
Exemple #8
0
    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"))
Exemple #9
0
    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'))
Exemple #10
0
    def testDissolutionWorkflow(self):
        # Create invivo data
        experimentStr = """
[EXPERIMENT] ===========================
comment = 
title = Dissolution

[VARIABLES] ============================
C ; none ; numeric[%f] ; measurement ; Concentration in solution (%)
t ; min ; numeric[%f] ; time ; Time in minutes since start

[VIAS] ================================

[DOSES] ================================

[GROUPS] ================================
__Profile

[SAMPLES] ================================
Profile; group=__Profile

[MEASUREMENTS] ===========================
Profile ; t; C
0 0 
2.5 1.7 
5 8.3 
7.5 13.3 
10 20.0 
20 44.0 
30 61.0 
40 70.7 
60 78.0 
80 79.7 
100 80.7 
120 80.0 
160 81.3 
200 82.0 
240 82.3 
"""
        fnExperiment = "experimentInVitro.pkpd"
        fhExperiment = open(fnExperiment, "w")
        fhExperiment.write(experimentStr)
        fhExperiment.close()

        print("Import Experiment in vitro")
        protImport = self.newProtocol(ProtImportExperiment,
                                      objLabel='pkpd - import experiment in vitro',
                                      inputFile=fnExperiment)
        self.launchProtocol(protImport)
        self.assertIsNotNone(protImport.outputExperiment.fnPKPD, "There was a problem with the import")
        self.validateFiles('protImport', protImport)

        os.remove(fnExperiment)

        # Fit a Weibull dissolution
        print("Fitting Weibull model ...")
        protWeibull = self.newProtocol(ProtPKPDDissolutionFit,
                                objLabel='pkpd - fit dissolution Weibull',
                                globalSearch=True, modelType=3)
        protWeibull.inputExperiment.set(protImport.outputExperiment)
        self.launchProtocol(protWeibull)
        self.assertIsNotNone(protWeibull.outputExperiment.fnPKPD, "There was a problem with the dissolution model ")
        self.assertIsNotNone(protWeibull.outputFitting.fnFitting, "There was a problem with the dissolution model ")
        self.validateFiles('ProtPKPDDissolutionFit', ProtPKPDDissolutionFit)
        experiment = PKPDExperiment()
        experiment.load(protWeibull.outputExperiment.fnPKPD)
        Vmax = float(experiment.samples['Profile'].descriptors['Vmax'])
        self.assertTrue(Vmax>80 and Vmax<82)
        lambdda = float(experiment.samples['Profile'].descriptors['lambda'])
        self.assertTrue(lambdda>0.009 and lambdda<0.011)
        b = float(experiment.samples['Profile'].descriptors['b'])
        self.assertTrue(b>1.4 and b<1.5)

        fitting = PKPDFitting()
        fitting.load(protWeibull.outputFitting.fnFitting)
        self.assertTrue(fitting.sampleFits[0].R2>0.997)

        # Create invivo data
        experimentStr = """
[EXPERIMENT] ===========================
comment = Generated as C(t)=D0/V*Ka/(Ka-Ke)*)(exp(-Ke*t)-exp(-Ka*t))
title = My experiment

[VARIABLES] ============================
Cp ; ug/L ; numeric[%f] ; measurement ; Plasma concentration
t ; min ; numeric[%f] ; time ; 

[VIAS] ================================
Oral; splineXY5;  tlag min; bioavailability=1.000000

[DOSES] ================================
Bolus1; via=Oral; bolus; t=0.000000 h; d=200 ug

[GROUPS] ================================
__Individual1

[SAMPLES] ================================
Individual1; dose=Bolus1; group=__Individual1

[MEASUREMENTS] ===========================
Individual1 ; t; Cp
"""
        t = np.arange(0,1000,10)
        Cp = unitResponse(100,50,0.05,0.2,t-20)+unitResponse(100,50,0.05,0.2,t-120)
        for n in range(t.size):
            experimentStr+="%f %f\n"%(t[n],Cp[n])
        fnExperiment ="experimentInVivo.pkpd"
        fhExperiment = open(fnExperiment,"w")
        fhExperiment.write(experimentStr)
        fhExperiment.close()

        print("Import Experiment in vivo")
        protImportInVivo = self.newProtocol(ProtImportExperiment,
                                      objLabel='pkpd - import experiment in vivo',
                                      inputFile=fnExperiment)
        self.launchProtocol(protImportInVivo)
        self.assertIsNotNone(protImportInVivo.outputExperiment.fnPKPD, "There was a problem with the import")
        self.validateFiles('protImport', protImportInVivo)

        os.remove(fnExperiment)

        # NCA numeric
        print("NCA numeric ...")
        protNCA = self.newProtocol(ProtPKPDNCANumeric,
                                objLabel='pkpd - nca numeric')
        protNCA.inputExperiment.set(protImportInVivo.outputExperiment)
        self.launchProtocol(protNCA)
        self.assertIsNotNone(protNCA.outputExperiment.fnPKPD, "There was a problem with the NCA numeric")
        self.validateFiles('prot', protNCA)
        experiment = PKPDExperiment()
        experiment.load(protNCA.outputExperiment.fnPKPD)
        AUC0t = float(experiment.samples['Individual1'].descriptors['AUC0t'])
        self.assertTrue(AUC0t > 960 and AUC0t < 980)
        AUMC0t = float(experiment.samples['Individual1'].descriptors['AUMC0t'])
        self.assertTrue(AUMC0t > 305000 and AUMC0t < 306000)
        Cmax = float(experiment.samples['Individual1'].descriptors['Cmax'])
        self.assertTrue(Cmax > 2.7 and Cmax < 2.9)
        Tmax = float(experiment.samples['Individual1'].descriptors['Tmax'])
        self.assertTrue(Tmax > 155 and Tmax < 165)
        MRT = float(experiment.samples['Individual1'].descriptors['MRT'])
        self.assertTrue(MRT > 314 and MRT < 315)

        # Fit Order 1
        print("Fitting splines5-monocompartment model ...")
        protModelInVivo = self.newProtocol(ProtPKPDMonoCompartment,
                                       objLabel='pkpd - fit monocompartment',
                                       bounds="(15.0, 30.0); (0.0, 400.0); (0.0, 1.0); (0.0, 1.0); (0.0, 1.0); (0.0, 1.0); (0.0, 1.0); (0.0, 1.0); (0.0, 1.0); (0.0, 1.0); (0.0, 1.0); (0.0, 1.0); (0.15, 0.25); (47, 53)"
                                       )
        protModelInVivo.inputExperiment.set(protImportInVivo.outputExperiment)
        self.launchProtocol(protModelInVivo)
        self.assertIsNotNone(protModelInVivo.outputExperiment.fnPKPD, "There was a problem with the PK model")
        self.assertIsNotNone(protModelInVivo.outputFitting.fnFitting, "There was a problem with the PK model")
        self.validateFiles('ProtPKPDMonoCompartment', ProtPKPDMonoCompartment)

        experiment = PKPDExperiment()
        experiment.load(protModelInVivo.outputExperiment.fnPKPD)
        V = float(experiment.samples['Individual1'].descriptors['V'])
        self.assertTrue(V>46 and V<54)
        Cl = float(experiment.samples['Individual1'].descriptors['Cl'])
        self.assertTrue(Cl>0.18 and Cl<0.22)

        fitting = PKPDFitting()
        fitting.load(protModelInVivo.outputFitting.fnFitting)
        self.assertTrue(fitting.sampleFits[0].R2>0.995)

        # Deconvolve the in vivo
        print("Deconvolving in vivo ...")
        protDeconv = self.newProtocol(ProtPKPDDeconvolve,
                                       objLabel='pkpd - deconvolution'
                                       )
        protDeconv.inputODE.set(protModelInVivo)
        self.launchProtocol(protDeconv)
        self.assertIsNotNone(protDeconv.outputExperiment.fnPKPD, "There was a problem with the deconvolution")
        self.validateFiles('ProtPKPDDeconvolve', ProtPKPDDeconvolve)

        # Levy plot
        print("Levy plot ...")
        protLevy = self.newProtocol(ProtPKPDDissolutionLevyPlot,
                                      objLabel='pkpd - levy plot'
                                      )
        protLevy.inputInVitro.set(protWeibull)
        protLevy.inputInVivo.set(protDeconv)
        self.launchProtocol(protLevy)
        self.assertIsNotNone(protLevy.outputExperiment.fnPKPD, "There was a problem with the Levy plot")
        self.validateFiles('ProtPKPDDissolutionLevyPlot', ProtPKPDDissolutionLevyPlot)

        # IVIVC
        print("In vitro-in vivo correlation ...")
        protIVIVC = self.newProtocol(ProtPKPDDissolutionIVIVC,
                                     timeScale=5,
                                     responseScale=1,
                                     objLabel='pkpd - ivivc'
                                    )
        protIVIVC.inputInVitro.set(protWeibull)
        protIVIVC.inputInVivo.set(protDeconv)
        self.launchProtocol(protIVIVC)
        self.assertIsNotNone(protIVIVC.outputExperimentFabs.fnPKPD, "There was a problem with the IVIVC")
        self.assertIsNotNone(protIVIVC.outputExperimentAdissol.fnPKPD, "There was a problem with the IVIVC")
        self.validateFiles('ProtPKPDDissolutionIVIVC', ProtPKPDDissolutionIVIVC)

        # IVIVC generic
        print("In vitro-in vivo generic ...")
        protIVIVCG = self.newProtocol(ProtPKPDDissolutionIVIVCGeneric,
                                      timeScale='$[k1]*$(t)+$[k2]*np.power($(t),2)+$[k3]*np.power($(t),3)',
                                      timeBounds='k1: [0,3]; k2: [-0.1,0.01];  k3: [0,1e-3]',
                                      responseScale='$[A]*$(Adissol)+$[B]+$[C]*np.power($(Adissol),2)',
                                      responseBounds='A: [0.01,1]; B: [-50,30]; C: [-0.05,0.05]',
                                      objLabel='pkpd - ivivc generic'
                                     )
        protIVIVCG.inputInVitro.set(protWeibull)
        protIVIVCG.inputInVivo.set(protDeconv)
        self.launchProtocol(protIVIVCG)
        self.assertIsNotNone(protIVIVCG.outputExperimentFabs.fnPKPD, "There was a problem with the IVIVC Generic")
        self.validateFiles('ProtPKPDDissolutionIVIVCG', ProtPKPDDissolutionIVIVCGeneric)

        # IVIVC splines
        print("In vitro-in vivo splies ...")
        protIVIVCS = self.newProtocol(ProtPKPDDissolutionIVIVCSplines,
                                      timeScale=1,
                                      responseScale=1,
                                      objLabel='pkpd - ivivc splines'
                                     )
        protIVIVCS.inputInVitro.set(protWeibull)
        protIVIVCS.inputInVivo.set(protDeconv)
        self.launchProtocol(protIVIVCS)
        self.assertIsNotNone(protIVIVCS.outputExperimentFabs.fnPKPD, "There was a problem with the IVIVC Splines")
        self.validateFiles('ProtPKPDDissolutionIVIVCS', ProtPKPDDissolutionIVIVCSplines)

        # Dissolution simulation
        print("IVIV+PK simulation ...")
        protIVIVPKL = self.newProtocol(ProtPKPDDissolutionPKSimulation,
                                      objLabel='pkpd - ivivc+pk',
                                      conversionType=1,
                                      inputN=1,
                                      tF=16.66,
                                      addIndividuals=True,
                                      inputDose=200
                                      )
        protIVIVPKL.inputInVitro.set(protWeibull.outputFitting)
        protIVIVPKL.inputPK.set(protModelInVivo.outputFitting)
        protIVIVPKL.inputLevy.set(protLevy.outputExperiment)
        self.launchProtocol(protIVIVPKL)
        self.assertIsNotNone(protIVIVPKL.outputExperiment.fnPKPD, "There was a problem with the simulation")
        self.validateFiles('ProtPKPDDissolutionPKSimulation', ProtPKPDDissolutionPKSimulation)

        # Dissolution simulation
        print("IVIV+PK simulation ...")
        protIVIVPKS = self.newProtocol(ProtPKPDDissolutionPKSimulation,
                                       objLabel='pkpd - ivivc+pk',
                                       inputN=1,
                                       tF=16.66,
                                       addIndividuals=True,
                                       inputDose=200
                                       )
        protIVIVPKS.inputInVitro.set(protWeibull.outputFitting)
        protIVIVPKS.inputPK.set(protModelInVivo.outputFitting)
        protIVIVPKS.inputIvIvC.set(protIVIVCS.outputExperimentFabs)
        self.launchProtocol(protIVIVPKS)
        self.assertIsNotNone(protIVIVPKS.outputExperiment.fnPKPD, "There was a problem with the simulation")
        self.validateFiles('ProtPKPDDissolutionPKSimulation', ProtPKPDDissolutionPKSimulation)

        # Internal validity
        print("Internal validity ...")
        protInternal = self.newProtocol(ProtPKPDIVIVCInternalValidity,
                                        objLabel='pkpd - internal validity')
        protInternal.inputExperiment.set(protNCA.outputExperiment)
        protInternal.inputSimulated.set(protIVIVPKL.outputExperiment)
        self.launchProtocol(protInternal)
        fnSummary = protInternal._getPath("summary.txt")
        self.assertTrue(os.path.exists(fnSummary))
        lineNo = 0
        for line in open(fnSummary).readlines():
            tokens = line.split('=')
            if lineNo == 0:
                AUCmean = np.abs(float(tokens[-1]))
                self.assertTrue(AUCmean < 20)
            elif lineNo == 1:
                Cmaxmean = np.abs(float(tokens[-1]))
                self.assertTrue(Cmaxmean < 13)
            lineNo += 1

        # Internal validity
        print("Internal validity ...")
        protInternal = self.newProtocol(ProtPKPDIVIVCInternalValidity,
                                    objLabel='pkpd - internal validity')
        protInternal.inputExperiment.set(protNCA.outputExperiment)
        protInternal.inputSimulated.set(protIVIVPKS.outputExperiment)
        self.launchProtocol(protInternal)
        fnSummary = protInternal._getPath("summary.txt")
        self.assertTrue(os.path.exists(fnSummary))
        lineNo = 0
        for line in open(fnSummary).readlines():
            tokens = line.split('=')
            if lineNo == 0:
                AUCmean = np.abs(float(tokens[-1]))
                self.assertTrue(AUCmean < 10)
            elif lineNo == 1:
                Cmaxmean = np.abs(float(tokens[-1]))
                self.assertTrue(Cmaxmean < 20)
            lineNo += 1
Exemple #11
0
class ProtPKPDApplyAllometricScaling(ProtPKPD):
    """ Apply an allometric scaling previously calculated to an incoming experiment. The labels specified by the
        allometric scaling model will be rescaled to the target weight. Note that depending on the exponent of the
        fitting you may want to use a different predictor (weight*maximum lifespan potential, or weight*brain weight)
        see the rule of exponents (Mahmood and Balian 1996). """

    _label = 'apply allometric'

    #--------------------------- DEFINE param functions --------------------------------------------
    def _defineParams(self, form):
        form.addSection('Input')
        form.addParam('inputPopulation', params.PointerParam, label="Input bootstrap population",
                      pointerClass='PKPDFitting',
                      help='The PK parameters of this experiment will be modified according to the allometric scale model.')
        form.addParam('inputAllometric', params.PointerParam, label="Allometric model", pointerClass='PKPDAllometricScale',
                      help='All variables specified by the allometric scale model will be adjusted')
        form.addParam('targetWeight', params.FloatParam, label="Target weight (kg)", default=25,
                      help='The PK parameters will be adjusted to this target weight')

    #--------------------------- INSERT steps functions --------------------------------------------
    def _insertAllSteps(self):
        self._insertFunctionStep('runAdjust', self.targetWeight.get())
        self._insertFunctionStep('createOutputStep')

    #--------------------------- STEPS functions --------------------------------------------
    def runAdjust(self, targetWeight):
        scaleModel = PKPDAllometricScale()
        scaleModel.load(self.inputAllometric.get().fnScale.get())

        self.population = self.readFitting(self.inputPopulation.get().fnFitting,cls="PKPDSampleFitBootstrap")
        self.experiment = PKPDExperiment()
        self.experiment.load(self.population.fnExperiment.get())

        for sampleFit in self.population.sampleFits:
            sample = self.experiment.samples[sampleFit.sampleName]
            sampleWeight = float(sample.getDescriptorValue(scaleModel.predictor))
            sample.setDescriptorValue(scaleModel.predictor,targetWeight)

            for varName, varUnits in scaleModel.averaged_vars:
                if varName in self.population.modelParameters:
                    idx = self.population.modelParameters.index(varName)
                    targetValue = scaleModel.models[varName][0]
                    sampleFit.parameters[0][idx] = targetValue

            for varName, varUnits in scaleModel.scaled_vars:
                if varName in self.population.modelParameters:
                    idx = self.population.modelParameters.index(varName)
                    k = scaleModel.models[varName][0]
                    a = scaleModel.models[varName][1]
                    targetValue = k*math.pow(targetWeight,a)
                    currentValue = k*math.pow(sampleWeight,a)
                    for j in range(sampleFit.parameters.shape[0]):
                        sampleFit.parameters[j][idx] *= targetValue/currentValue

        self.experiment.write(self._getPath("experiment.pkpd"))
        self.population.fnExperiment.set(self._getPath("experiment.pkpd"))
        self.population.write(self._getPath("bootstrapPopulation.pkpd"))

    def createOutputStep(self):
        self._defineOutputs(outputExperiment=self.experiment)
        self._defineOutputs(outputPopulation=self.population)
        self._defineSourceRelation(self.inputPopulation, self.experiment)
        self._defineSourceRelation(self.inputAllometric, self.experiment)
        self._defineSourceRelation(self.inputPopulation, self.population)
        self._defineSourceRelation(self.inputAllometric, self.population)

    #--------------------------- INFO functions --------------------------------------------
    def _summary(self):
        msg = ["Target weight: %f"%self.targetWeight.get()]
        return msg

    def _citations(self):
        return ['Sharma2009','Mahmood1996']
Exemple #12
0
    def simulate(self, objId1, objId2, inputDose, inputN):
        import sys
        self.getInVitroModels()
        self.getScaling()
        self.getPKModels()

        if not self.usePKExperiment:
            otherPKExperiment = PKPDExperiment()
            otherPKExperiment.load(self.inputPKOtherExperiment.get().fnPKPD)

        self.outputExperiment = PKPDExperiment()
        tvar = PKPDVariable()
        tvar.varName = "t"
        tvar.varType = PKPDVariable.TYPE_NUMERIC
        tvar.role = PKPDVariable.ROLE_TIME
        tvar.units = createUnit(self.fittingPK.predictor.units.unit)

        self.Cunits = self.fittingPK.predicted.units
        self.AUCunits = multiplyUnits(tvar.units.unit, self.Cunits.unit)
        self.AUMCunits = multiplyUnits(tvar.units.unit, self.AUCunits)
        if self.addIndividuals.get():
            self.outputExperiment.variables["t"] = tvar
            self.outputExperiment.variables[
                self.fittingPK.predicted.varName] = self.fittingPK.predicted
            self.outputExperiment.general[
                "title"] = "Simulated ODE response from IVIVC dissolution profiles"
            self.outputExperiment.general[
                "comment"] = "Simulated ODE response from IVIVC dissolution profiles"
            for via, _ in self.pkModel.drugSource.vias:
                self.outputExperiment.vias[via.viaName] = via
            for dose in self.pkModel.drugSource.parsedDoseList:
                self.outputExperiment.doses[dose.doseName] = dose

            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)

            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

        t = np.arange(self.pkModel.t0, self.pkModel.tF, 1)

        if self.usePKExperiment:
            NPKFits = len(self.fittingPK.sampleFits)
            invivoFits = self.fittingPK.sampleFits
        else:
            NPKFits = len(otherPKExperiment.samples)
            invivoFits = [x for x in otherPKExperiment.samples.values()]
            for sample in invivoFits:
                sample.parameters = [
                    float(x) for x in sample.getDescriptorValues(
                        self.fittingPK.modelParameters)
                ]

        NDissolFits = len(self.fittingInVitro.sampleFits)

        if self.allCombinations:
            inputN = NPKFits * NDissolFits

        AUCarray = np.zeros(inputN)
        AUMCarray = np.zeros(inputN)
        MRTarray = np.zeros(inputN)
        CmaxArray = np.zeros(inputN)
        TmaxArray = np.zeros(inputN)

        for i in range(0, inputN):
            print("Simulation no. %d ----------------------" % i)

            # Get a random PK model
            if self.allCombinations:
                nfit = int(i / NDissolFits)
            else:
                nfit = int(random.uniform(0, NPKFits))
            sampleFitVivo = invivoFits[nfit]
            print("In vivo sample name=", sampleFitVivo.sampleName)
            if self.pkPopulation:
                nbootstrap = int(
                    random.uniform(0, sampleFitVivo.parameters.shape[0]))
                pkPrmAll = sampleFitVivo.parameters[nbootstrap, :]
            else:
                pkPrmAll = sampleFitVivo.parameters
            pkPrm = pkPrmAll[-self.pkNParams:]  # Get the last Nparams
            print("PK parameters: ", pkPrm)

            tlag = 0
            if self.includeTlag.get() and (not self.tlagIdx is None):
                tlag = pkPrmAll[self.tlagIdx]
                print("tlag: ", tlag)
            bioavailability = 1
            if not self.bioavailabilityIdx is None:
                bioavailability = pkPrmAll[self.bioavailabilityIdx]
                print("bioavailability: ", bioavailability)

            # Get a dissolution profile
            if self.allCombinations:
                nfit = i % NDissolFits
            else:
                nfit = int(random.uniform(0, NDissolFits))
            sampleFitVitro = self.fittingInVitro.sampleFits[nfit]
            if self.dissolutionPopulation:
                nbootstrap = int(
                    random.uniform(0, sampleFitVitro.parameters.shape[0]))
                dissolutionPrm = sampleFitVitro.parameters[nbootstrap, :]
            else:
                dissolutionPrm = sampleFitVitro.parameters
            print(
                "Dissolution parameters: ",
                np.array2string(np.asarray(dissolutionPrm, dtype=np.float64),
                                max_line_width=1000))
            sys.stdout.flush()

            if sampleFitVivo.sampleName in self.allTimeScalings:
                keyToUse = sampleFitVivo.sampleName
            elif len(self.allTimeScalings) == 1:
                keyToUse = list(self.allTimeScalings.keys())[0]
            else:
                raise Exception("Cannot find %s in the scaling keys" %
                                sampleFitVivo.sampleName)
            nfit = int(random.uniform(0, len(self.allTimeScalings[keyToUse])))

            tvitroLevy, tvivoLevy = self.allTimeScalings[keyToUse][nfit]
            tvivoLevyUnique, tvitroLevyUnique = uniqueFloatValues(
                tvivoLevy, tvitroLevy)
            BLevy = InterpolatedUnivariateSpline(tvivoLevyUnique,
                                                 tvitroLevyUnique,
                                                 k=1)

            tvitro = np.asarray(BLevy(t), dtype=np.float64)
            A = np.clip(
                self.dissolutionModel.forwardModel(dissolutionPrm, tvitro)[0],
                0, 100)

            if self.conversionType.get() == 0:
                # In vitro-in vivo correlation
                Adissol, Fabs = self.allResponseScalings[keyToUse][nfit]
                AdissolUnique, FabsUnique = uniqueFloatValues(Adissol, Fabs)
                B = InterpolatedUnivariateSpline(AdissolUnique,
                                                 FabsUnique,
                                                 k=1)
                A = np.asarray(B(A), dtype=np.float64)

            # Set the dissolution profile
            self.pkModel.drugSource.getVia().viaProfile.setXYValues(t, A)
            C = self.pkModel.forwardModel(
                pkPrm, [t])[0]  # forwardModel returns a list of arrays
            if tlag != 0.0:
                B = interp1d(t, C)
                C = B(np.clip(t - tlag, 0.0, None))
                C[0:int(tlag)] = 0.0
            C *= bioavailability

            self.NCA(t, C)
            AUCarray[i] = self.AUC0t
            AUMCarray[i] = self.AUMC0t
            MRTarray[i] = self.MRT
            CmaxArray[i] = self.Cmax
            TmaxArray[i] = self.Tmax

            if self.addIndividuals:
                self.addSample(
                    "Simulation_%d" % i, t, C, "%s---%s" %
                    (sampleFitVivo.sampleName, sampleFitVitro.sampleName))

        # Report NCA statistics
        alpha_2 = (100 - 95) / 2
        limits = np.percentile(AUCarray, [alpha_2, 100 - alpha_2])
        fhSummary = open(self._getPath("summary.txt"), "w")
        self.doublePrint(
            fhSummary, "AUC %f%% confidence interval=[%f,%f] [%s] mean=%f" %
            (95, 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" %
            (95, 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" %
            (95, limits[0], limits[1], strUnit(
                self.timeUnits), np.mean(MRTarray)))
        limits = np.percentile(CmaxArray, [alpha_2, 100 - alpha_2])
        self.doublePrint(
            fhSummary, "Cmax %f%% confidence interval=[%f,%f] [%s] mean=%f" %
            (95, limits[0], limits[1], strUnit(
                self.Cunits.unit), np.mean(CmaxArray)))
        limits = np.percentile(TmaxArray, [alpha_2, 100 - alpha_2])
        self.doublePrint(
            fhSummary, "Tmax %f%% confidence interval=[%f,%f] [%s] mean=%f" %
            (95, limits[0], limits[1], strUnit(
                self.timeUnits), np.mean(TmaxArray)))
        fhSummary.close()

        if self.addIndividuals:
            self.outputExperiment.write(self._getPath("experiment.pkpd"),
                                        writeToExcel=False)