예제 #1
0
    def solve(self, objId1):
        self.experiment = self.readExperiment(self.inputExperiment.get().fnPKPD)

        # Create output object
        self.outputExperiment = None

        timeRange = self.experiment.getRange(self.timeVar.get())
        for sampleName, sample in self.experiment.samples.items():
            # Get t, A
            t=np.asarray(sample.getValues(self.timeVar.get()),dtype=np.float64)
            A=np.asarray(sample.getValues(self.amountVar.get()),dtype=np.float64)
            if t[0]>0:
                t=np.insert(t,0,0) # Add (0,0) to the profile
                A=np.insert(A,0,0)
            t, A = uniqueFloatValues(t, A)
            if self.resampleT.get()>0:
                B = InterpolatedUnivariateSpline(t, A, k=1)
                t = np.arange(np.min(t),np.max(t)+self.resampleT.get(),self.resampleT.get())
                A = B(t)

            # Find C and Cp
            C, Cp = self.calculateConcentrations2(t,A)

            if self.outputExperiment is None:
                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)

                Cvar = PKPDVariable()
                Cvar.varName = "C"
                Cvar.varType = PKPDVariable.TYPE_NUMERIC
                Cvar.role = PKPDVariable.ROLE_MEASUREMENT
                Lunits = createUnit("L")
                Cvar.units = createUnit(divideUnits(self.experiment.getVarUnits(self.amountVar.get()),Lunits.unit))
                Cvar.comment = "Concentration central compartment"

                Cpvar = PKPDVariable()
                Cpvar.varName = "Cp"
                Cpvar.varType = PKPDVariable.TYPE_NUMERIC
                Cpvar.role = PKPDVariable.ROLE_MEASUREMENT
                Cpvar.units = createUnit(divideUnits(self.experiment.getVarUnits(self.amountVar.get()),Lunits.unit))
                Cpvar.comment = "Concentration peripheral compartment"

                self.outputExperiment.variables[tvar.varName] = tvar
                self.outputExperiment.variables[Cvar.varName] = Cvar
                self.outputExperiment.variables[Cpvar.varName] = Cpvar
                self.outputExperiment.general["title"]="Inverse Loo-Riegelman"
                self.outputExperiment.general["comment"]=""

            self.addSample(sampleName,t,C,Cp)

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
예제 #2
0
    def createOutputExperiment(self):
        tvitroVar = PKPDVariable()
        tvitroVar.varName = "tvitro"
        tvitroVar.varType = PKPDVariable.TYPE_NUMERIC
        tvitroVar.role = PKPDVariable.ROLE_TIME
        tvitroVar.units = createUnit(self.experimentInVivo.getTimeUnits().unit)
        tvitroVar.comment = "tvitro"

        AdissolVar = PKPDVariable()
        AdissolVar.varName = "Adissol"
        AdissolVar.varType = PKPDVariable.TYPE_NUMERIC
        AdissolVar.role = PKPDVariable.ROLE_MEASUREMENT
        AdissolVar.units = createUnit(PKPDUnit.UNIT_NONE)
        AdissolVar.comment = "Amount disolved in vitro"

        self.outputExperiment = PKPDExperiment()
        self.outputExperiment.variables[tvitroVar.varName] = tvitroVar
        self.outputExperiment.variables[AdissolVar.varName] = AdissolVar
        self.outputExperiment.general["title"] = "In-vitro target simulation"
        self.outputExperiment.general["comment"] = ""
예제 #3
0
    def deconvolve(self, objId1):
        self.experiment = self.readExperiment(
            self.inputExperiment.get().fnPKPD)

        # 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)

        Avar = PKPDVariable()
        Avar.varName = "A"
        Avar.varType = PKPDVariable.TYPE_NUMERIC
        Avar.role = PKPDVariable.ROLE_MEASUREMENT
        Avar.units = createUnit("none")

        self.outputExperiment.variables[tvar.varName] = tvar
        self.outputExperiment.variables[Avar.varName] = Avar
        self.outputExperiment.general[
            "title"] = "Deconvolution of the amount released"
        self.outputExperiment.general[
            "comment"] = "Amount released at any time t"

        # Get the input sample from another experiment if necessary
        sampleFrom = None
        if self.externalIV.get() == self.ANOTHER_INPUT:
            anotherExperiment = self.readExperiment(
                self.externalIVODE.get().outputExperiment.fnPKPD)
            for _, sampleFrom in anotherExperiment.samples.items(
            ):  # Take the first sample from the reference
                break

        timeRange = self.experiment.getRange(self.timeVar.get())
        for sampleName, sample in self.experiment.samples.items():
            # Get t, Cp
            t = np.asarray(sample.getValues(self.timeVar.get()),
                           dtype=np.float64)
            Cp = np.asarray(sample.getValues(self.concVar.get()),
                            dtype=np.float64)
            Cp = np.clip(Cp, 0.0, None)
            t = np.insert(t, 0, 0)  # Add (0,0) to the profile
            Cp = np.insert(Cp, 0, 0)
            t, Cp = uniqueFloatValues(t, Cp)
            if self.resampleT.get() > 0:
                B = InterpolatedUnivariateSpline(t, Cp, k=1)
                t = np.arange(np.min(t),
                              np.max(t) + self.resampleT.get(),
                              self.resampleT.get())
                Cp = B(t)

            # Calculate AUC0t
            AUC0t = calculateAUC0t(t, Cp)
            AUC0inf = float(AUC0t[-1])

            # Calculate peripheral
            if self.externalIV.get() == self.SAME_INPUT:
                sampleFrom = sample
            Cl = float(sampleFrom.descriptors['Cl'])
            V = float(sampleFrom.descriptors['V'])
            Clp = float(sampleFrom.descriptors['Clp'])
            Vp = float(sampleFrom.descriptors['Vp'])
            k12 = Clp / V
            k21 = Clp / Vp
            Cperipheral = self.calculateCperipheral(t, Cp, k12, k21)

            # Deconvolve
            k10 = Cl / V
            A = (Cp + Cperipheral + k10 * AUC0t) / k10
            if self.normalize.get():
                A *= 100 / AUC0inf
                if self.saturate.get():
                    A = np.clip(A, None, 100.0)
            A = np.clip(A, 0, None)
            if self.smooth:
                if t[0] > 0:
                    t = np.insert(t, 0, 0)
                    A = np.insert(A, 0, 0)
                if self.saturate.get() and self.normalize.get():
                    A = np.clip(A, None, 100.0)
                A = np.clip(smoothPchip(t, A), 0, None)

            if self.considerBioaval.get() == self.BIOAVAIL_DIV:
                A /= sample.getBioavailability()
            elif self.considerBioaval.get() == self.BIOAVAIL_MULT:
                A *= sample.getBioavailability()
            self.addSample(sampleName, t, A)

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
예제 #4
0
    def runAnalysis(self, objId, xvarName):
        self.outputExperiment = self.readExperiment(
            self.inputExperiment.get().fnPKPD)

        tvarName = None
        for varName in self.outputExperiment.variables:
            if self.outputExperiment.variables[
                    varName].role == PKPDVariable.ROLE_TIME:
                tvarName = varName
                break
        if tvarName is None:
            raise Exception("Cannot find a time variable in this experiment")

        tvar = PKPDVariable()
        tvar.varName = "t"
        tvar.varType = PKPDVariable.TYPE_NUMERIC
        tvar.role = PKPDVariable.ROLE_TIME
        self.tunits = self.outputExperiment.getTimeUnits().unit
        tvar.units = createUnit(self.tunits)

        self.Cunits = self.outputExperiment.variables[xvarName].units
        self.AUCunits = multiplyUnits(tvar.units.unit, self.Cunits.unit)
        self.AUMCunits = multiplyUnits(tvar.units.unit, self.AUCunits)

        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

        inputN = len(self.outputExperiment.samples)
        AUCarray = np.zeros(inputN)
        AUMCarray = np.zeros(inputN)
        MRTarray = np.zeros(inputN)
        CmaxArray = np.zeros(inputN)
        TmaxArray = np.zeros(inputN)
        i = 0
        for sampleName, sample in self.outputExperiment.samples.items():
            [t, Cp] = sample.getXYValues(tvarName, xvarName)
            print("Analyzing %s" % sampleName)
            self.analyzeSample(sample, t[0], Cp[0])

            AUCarray[i] = self.AUC0t
            AUMCarray[i] = self.AUMC0t
            MRTarray[i] = self.MRT
            CmaxArray[i] = self.Cmax
            TmaxArray[i] = self.Tmax
            i += 1

        # 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] [min] mean=%f" %
            (95, limits[0], limits[1], 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] [min] mean=%f" %
            (95, limits[0], limits[1], np.mean(TmaxArray)))
        fhSummary.close()

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
예제 #5
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'))
예제 #6
0
    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)
예제 #7
0
    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"))
예제 #8
0
    def deconvolve(self, objId):
        self.protODE = self.inputODE.get()
        self.experiment = self.readExperiment(self.protODE.outputExperiment.fnPKPD)
        self.fitting = self.readFitting(self.protODE.outputFitting.fnFitting)
        self.varNameX = self.fitting.predictor.varName
        self.varNameY = self.fitting.predicted.varName

        # Create drug source
        self.clearGroupParameters()
        self.createDrugSource()

        # 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)

        Avar = PKPDVariable()
        Avar.varName = "A"
        Avar.varType = PKPDVariable.TYPE_NUMERIC
        Avar.role = PKPDVariable.ROLE_MEASUREMENT
        if self.normalize.get():
            Avar.units = createUnit("none")
        else:
            Avar.units = createUnit(self.experiment.getDoseUnits())

        self.outputExperiment.variables[tvar.varName] = tvar
        self.outputExperiment.variables[Avar.varName] = Avar
        self.outputExperiment.general["title"]="Deconvolution of the amount released"
        self.outputExperiment.general["comment"]="Amount released at any time t"

        # Simulate the different responses
        timeRange = self.experiment.getRange(self.varNameX)
        deltaT = 0.5
        t = np.arange(0.0,timeRange[1],deltaT)
        for sampleName, sample in self.experiment.samples.items():
            self.printSection("Deconvolving "+sampleName)
            sample.interpretDose()
            drugSource = DrugSource()
            drugSource.setDoses(sample.parsedDoseList, 0.0, timeRange[1])

            p=[]
            tlag=0
            for paramName in drugSource.getParameterNames():
                p.append(float(sample.getDescriptorValue(paramName)))
                if paramName.endswith('_tlag') and self.removeTlag.get():
                    tlag=float(sample.getDescriptorValue(paramName))
            drugSource.setParameters(p)

            cumulatedDose=0.0
            A=t*0.0 # Allocate memory
            totalReleased = drugSource.getAmountReleasedUpTo(10*t[-1])
            print("t(min) A(%s)"%Avar.units._toString())
            for i in range(t.size):
                cumulatedDose+=drugSource.getAmountReleasedAt(t[i],deltaT)
                A[i]=cumulatedDose
                if self.normalize.get():
                    A[i] *= 100.0/totalReleased
                print("%f %f"%(t[i],A[i]))
                # print("%f %f %f %f"%(t[i], A[i], drugSource.getAmountReleasedAt(t[i], 0.5), drugSource.getAmountReleasedUpTo(t[i] + 0.5)))
            if self.saturate.get() and self.normalize.get():
                A = np.clip(A,None,100.0)
            if self.considerBioaval.get()==self.BIOAVAIL_DIV:
                A /= sample.getBioavailability()
            elif self.considerBioaval.get()==self.BIOAVAIL_MULT:
                A *= sample.getBioavailability()
            self.addSample(sampleName,t-tlag,A)

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
예제 #9
0
    def deconvolve(self, objId):
        self.protODE = self.inputODE.get()
        self.experiment = self.readExperiment(self.protODE.outputExperiment.fnPKPD)
        self.fitting = self.readFitting(self.protODE.outputFitting.fnFitting)
        self.varNameX = self.fitting.predictor.varName
        self.varNameY = self.fitting.predicted.varName

        # Create drug source
        self.clearGroupParameters()
        self.createDrugSource()

        # 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)

        Avar = PKPDVariable()
        Avar.varName = "A"
        Avar.varType = PKPDVariable.TYPE_NUMERIC
        Avar.role = PKPDVariable.ROLE_MEASUREMENT
        if self.normalize.get():
            Avar.units = createUnit("none")
        else:
            Avar.units = createUnit(self.experiment.getDoseUnits())

        self.outputExperiment.variables[tvar.varName] = tvar
        self.outputExperiment.variables[Avar.varName] = Avar
        self.outputExperiment.general["title"]="Deconvolution of the amount released"
        self.outputExperiment.general["comment"]="Amount released at any time t"

        # Create PK model
        timeRange = self.experiment.getRange(self.varNameX)
        deltaT = 0.5
        t = np.arange(0.0,timeRange[1]*5+deltaT,deltaT)

        model = self.protODE.createModel()
        model.setExperiment(self.experiment)
        model.deltaT = deltaT
        model.setXVar(self.varNameX)
        model.setYVar(self.varNameY)
        model.x = t
        model.t0=0
        model.tF=np.max(t)
        prmNames = model.getParameterNames()

        if len(self.experiment.samples)==0:
            print("Cannot find any sample in the experiment")
            return

        # Create unit dose
        drugSource = DrugSource()
        dose=None
        for sampleName, sample in self.experiment.samples.items():
            sample.interpretDose()
            if len(sample.parsedDoseList)>0:
                dose = createDeltaDose(1.0, via=createVia("Intravenous; iv", self.experiment),
                                       dunits=sample.parsedDoseList[0].dunits)
        if dose is None:
            print("Cannot find any dose among the samples")
            return
        drugSource.setDoses([dose], 0.0, timeRange[1])
        model.drugSource = drugSource

        # Get the input sample from another experiment if necessary
        sampleFrom = None
        if self.externalIV.get() == self.ANOTHER_INPUT:
            anotherExperiment = self.readExperiment(self.externalIVODE.get().outputExperiment.fnPKPD)
            for _, sampleFrom in anotherExperiment.samples.items(): # Take the first sample from the reference
                break

        # Simulate the different responses
        for sampleName, sample in self.experiment.samples.items():
            self.printSection("Deconvolving "+sampleName)
            drugSourceSample = DrugSource()
            drugSourceSample.setDoses(sample.parsedDoseList, 0.0, timeRange[1])

            p=[]
            tlag=0
            for paramName in drugSourceSample.getParameterNames():
                p.append(float(sample.getDescriptorValue(paramName)))
                if paramName.endswith('_tlag') and self.removeTlag.get():
                    tlag=float(sample.getDescriptorValue(paramName))
            drugSourceSample.setParameters(p)

            if self.externalIV.get()==self.SAME_INPUT:
                sampleFrom = sample
            parameters=[]
            for prmName in prmNames:
                parameters.append(float(sampleFrom.descriptors[prmName]))
            model.setParameters(parameters)
            h = model.forwardModel(parameters, [t]*model.getResponseDimension())[0]

            ts,Cs = sample.getXYValues(self.varNameX,self.varNameY)
            ts=np.insert(ts,0,0.0)
            Cs=np.insert(Cs,0,0.0)
            ts, Cs = uniqueFloatValues(ts,Cs)
            B=InterpolatedUnivariateSpline(ts, Cs, k=1)
            C=np.clip(B(t),0.0,None)

            Fabs=np.clip(np.real(ifft(np.divide(fft(C),fft(h)))),0.0,None)

            cumulatedDose=0.0
            A=t*0.0 # Allocate memory
            totalReleased = drugSourceSample.getAmountReleasedUpTo(10*t[-1]) # Divided by 100 to have a number between 0 and 100
            print("Total amount released: %f"%totalReleased)
            print("t(min) A(%s)"%Avar.units._toString())
            for i in range(t.size):
                cumulatedDose+=Fabs[i]
                A[i]=cumulatedDose
                if self.normalize.get():
                    A[i] *= 100.0/totalReleased
                print("%f %f"%(t[i],A[i]))
                # print("%f %f %f %f"%(t[i], A[i], drugSource.getAmountReleasedAt(t[i], 0.5), drugSource.getAmountReleasedUpTo(t[i] + 0.5)))
            if self.saturate.get() and self.normalize.get():
                A = np.clip(A,None,100.0)
            if self.considerBioaval.get()==self.BIOAVAIL_DIV:
                A /= sample.getBioavailability()
            elif self.considerBioaval.get()==self.BIOAVAIL_MULT:
                A *= sample.getBioavailability()
            As, ts = uniqueFloatValues(np.clip(A,0,None),t-tlag)
            self.addSample(sampleName,ts,As)

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
예제 #10
0
    def createOutputExperiments(self, set):
        tvitroVar = PKPDVariable()
        tvitroVar.varName = "tvitro"
        tvitroVar.varType = PKPDVariable.TYPE_NUMERIC
        tvitroVar.role = PKPDVariable.ROLE_TIME
        tvitroVar.units = createUnit(
            self.experimentInVitro.getTimeUnits().unit)
        tvitroVar.comment = "tvitro"

        tvivoVar = PKPDVariable()
        tvivoVar.varName = "tvivo"
        tvivoVar.varType = PKPDVariable.TYPE_NUMERIC
        tvivoVar.role = PKPDVariable.ROLE_TIME
        tvivoVar.units = createUnit(self.experimentInVivo.getTimeUnits().unit)
        tvivoVar.comment = "tvivo"

        tvitroReinterpolatedVar = PKPDVariable()
        tvitroReinterpolatedVar.varName = "tvitroReinterpolated"
        tvitroReinterpolatedVar.varType = PKPDVariable.TYPE_NUMERIC
        tvitroReinterpolatedVar.role = PKPDVariable.ROLE_TIME
        tvitroReinterpolatedVar.units = createUnit(
            self.experimentInVitro.getTimeUnits().unit)
        tvitroReinterpolatedVar.comment = "tvitro reinterpolated"

        tvivoReinterpolatedVar = PKPDVariable()
        tvivoReinterpolatedVar.varName = "tvivoReinterpolated"
        tvivoReinterpolatedVar.varType = PKPDVariable.TYPE_NUMERIC
        tvivoReinterpolatedVar.role = PKPDVariable.ROLE_TIME
        tvivoReinterpolatedVar.units = createUnit(
            self.experimentInVivo.getTimeUnits().unit)
        tvivoReinterpolatedVar.comment = "tvivo reinterpolated"

        AdissolVar = PKPDVariable()
        AdissolVar.varName = "Adissol"
        AdissolVar.varType = PKPDVariable.TYPE_NUMERIC
        AdissolVar.role = PKPDVariable.ROLE_MEASUREMENT
        AdissolVar.units = createUnit(
            self.experimentInVitro.getVarUnits(self.varNameY))
        AdissolVar.comment = "Amount disolved in vitro"

        FabsVar = PKPDVariable()
        FabsVar.varName = "Fabs"
        FabsVar.varType = PKPDVariable.TYPE_NUMERIC
        FabsVar.role = PKPDVariable.ROLE_MEASUREMENT
        FabsVar.units = createUnit(self.experimentInVivo.getVarUnits("A"))
        FabsVar.comment = "Amount absorbed in vivo"

        AdissolReinterpolatedVar = PKPDVariable()
        AdissolReinterpolatedVar.varName = "AdissolReinterpolated"
        AdissolReinterpolatedVar.varType = PKPDVariable.TYPE_NUMERIC
        AdissolReinterpolatedVar.role = PKPDVariable.ROLE_MEASUREMENT
        AdissolReinterpolatedVar.units = createUnit(
            self.experimentInVitro.getVarUnits(self.varNameY))
        AdissolReinterpolatedVar.comment = "Time reinterpolated amount disolved in vitro"

        FabsReinterpolatedVar = PKPDVariable()
        FabsReinterpolatedVar.varName = "FabsReinterpolated"
        FabsReinterpolatedVar.varType = PKPDVariable.TYPE_NUMERIC
        FabsReinterpolatedVar.role = PKPDVariable.ROLE_MEASUREMENT
        FabsReinterpolatedVar.units = createUnit(
            self.experimentInVivo.getVarUnits("A"))
        FabsReinterpolatedVar.comment = "Time reinterpolated amount absorbed in vivo"

        AdissolPredictedVar = PKPDVariable()
        AdissolPredictedVar.varName = "AdissolPredicted"
        AdissolPredictedVar.varType = PKPDVariable.TYPE_NUMERIC
        AdissolPredictedVar.role = PKPDVariable.ROLE_MEASUREMENT
        AdissolPredictedVar.units = createUnit(
            self.experimentInVitro.getVarUnits(self.varNameY))
        AdissolPredictedVar.comment = "Predicted amount disolved in vitro"

        FabsPredictedVar = PKPDVariable()
        FabsPredictedVar.varName = "FabsPredicted"
        FabsPredictedVar.varType = PKPDVariable.TYPE_NUMERIC
        FabsPredictedVar.role = PKPDVariable.ROLE_MEASUREMENT
        FabsPredictedVar.units = createUnit(
            self.experimentInVivo.getVarUnits("A"))
        FabsPredictedVar.comment = "Predicted amount absorbed in vivo"

        if set == 1:
            self.outputExperimentFabs = PKPDExperiment()
            self.outputExperimentFabs.variables[
                tvitroReinterpolatedVar.varName] = tvitroReinterpolatedVar
            self.outputExperimentFabs.variables[
                AdissolReinterpolatedVar.varName] = AdissolReinterpolatedVar
            self.outputExperimentFabs.variables[tvivoVar.varName] = tvivoVar
            self.outputExperimentFabs.variables[FabsVar.varName] = FabsVar
            self.outputExperimentFabs.variables[
                FabsPredictedVar.varName] = FabsPredictedVar
            self.outputExperimentFabs.general[
                "title"] = "In-vitro In-vivo correlation"
            self.outputExperimentFabs.general[
                "comment"] = "Fabs vs Predicted Fabs"

            self.outputExperimentAdissol = PKPDExperiment()
            self.outputExperimentAdissol.variables[
                tvivoReinterpolatedVar.varName] = tvivoReinterpolatedVar
            self.outputExperimentAdissol.variables[
                FabsReinterpolatedVar.varName] = FabsReinterpolatedVar
            self.outputExperimentAdissol.variables[
                tvitroVar.varName] = tvitroVar
            self.outputExperimentAdissol.variables[
                AdissolVar.varName] = AdissolVar
            self.outputExperimentAdissol.variables[
                AdissolPredictedVar.varName] = AdissolPredictedVar
            self.outputExperimentAdissol.general[
                "title"] = "In-vitro In-vivo correlation"
            self.outputExperimentAdissol.general[
                "comment"] = "Adissol vs Predicted Adissol"
        else:
            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.general[
                "title"] = "In-vitro In-vivo correlation"
            self.outputExperimentFabsSingle.general[
                "comment"] = "Fabs vs Predicted Fabs"
예제 #11
0
    def calculateAllLevy(self, objId1, objId2):
        parametersInVitro, vesselNames, tvitroMax = self.getInVitroModels()
        profilesInVivo, sampleNames = self.getInVivoProfiles()

        self.outputExperiment = PKPDExperiment()
        tvitrovar = PKPDVariable()
        tvitrovar.varName = "tvitro"
        tvitrovar.varType = PKPDVariable.TYPE_NUMERIC
        tvitrovar.role = PKPDVariable.ROLE_MEASUREMENT
        tvitrovar.units = createUnit(
            self.experimentInVitro.getTimeUnits().unit)

        tvivovar = PKPDVariable()
        tvivovar.varName = "tvivo"
        tvivovar.varType = PKPDVariable.TYPE_NUMERIC
        tvivovar.role = PKPDVariable.ROLE_MEASUREMENT
        tvivovar.units = createUnit(self.experimentInVivo.getTimeUnits().unit)

        self.outputExperiment.variables[tvivovar.varName] = tvivovar
        self.outputExperiment.variables[tvitrovar.varName] = tvitrovar
        self.outputExperiment.general["title"] = "Levy plots"
        self.outputExperiment.general[
            "comment"] = "Time in vivo vs time in vitro"

        i = 1
        levyList = []
        for parameterInVitro, vesselFrom, tvitroMaxi in izip(
                parametersInVitro, vesselNames, tvitroMax):
            for aux, sampleFrom in izip(profilesInVivo, sampleNames):
                t, profileInVivo = aux
                tvitro, tvivo, _ = self.produceLevyPlot(
                    t, parameterInVitro, profileInVivo, tvitroMaxi)
                tvitroUnique, tvivoUnique = twoWayUniqueFloatValues(
                    tvitro, tvivo)
                idx = np.logical_and(tvitroUnique > 0, tvivoUnique > 0)
                tvitroUnique = tvitroUnique[idx]
                tvivoUnique = tvivoUnique[idx]
                if tvitroUnique[0] > 0 and tvivoUnique[0] > 0:
                    tvitroUnique = np.insert(tvitroUnique, 0, 0.0)
                    tvivoUnique = np.insert(tvivoUnique, 0, 0.0)
                levyName = "levy_%04d" % i
                levyList.append((tvitroUnique, tvivoUnique))
                self.addSample(self.outputExperiment, levyName, tvitroUnique,
                               tvivoUnique, sampleFrom, vesselFrom)

                self.makeSuggestions(levyName, tvitroUnique, tvivoUnique)
                i += 1

        self.outputExperiment.write(self._getPath("experiment.pkpd"))

        # Single Levy plot
        self.outputExperimentSingle = PKPDExperiment()
        self.outputExperimentSingle.variables[tvivovar.varName] = tvivovar
        self.outputExperimentSingle.variables[tvitrovar.varName] = tvitrovar
        self.outputExperimentSingle.general["title"] = "Levy plots"
        self.outputExperimentSingle.general[
            "comment"] = "Time in vivo vs time in vitro"

        tvitroSingle, tvivoSingle = computeXYmean(levyList)
        tvitroUnique, tvivoUnique = twoWayUniqueFloatValues(
            tvitroSingle, tvivoSingle)
        idx = np.logical_and(tvitroUnique > 0, tvivoUnique > 0)
        tvitroUnique = tvitroUnique[idx]
        tvivoUnique = tvivoUnique[idx]
        if tvitroUnique[0] > 0 and tvivoUnique[0] > 0:
            tvitroUnique = np.insert(tvitroUnique, 0, 0.0)
            tvivoUnique = np.insert(tvivoUnique, 0, 0.0)

        self.addSample(self.outputExperimentSingle, "levyAvg", tvitroUnique,
                       tvivoUnique, "vivoAvg", "vitroAvg")

        self.outputExperimentSingle.write(
            self._getPath("experimentSingle.pkpd"))
예제 #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)
예제 #13
0
    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"))